Android app拍照后给图片加水印大小随着图片大小固定比例 具体代码
时间: 2023-08-04 22:09:27 浏览: 247
以下是一个简单的示例代码,可以在 Android 应用程序中拍照并添加水印。其中水印的大小随着图片大小固定比例,具体代码如下:
```java
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE_CAPTURE = 1;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.image_view);
Button btnCamera = findViewById(R.id.btn_camera);
btnCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Bitmap watermarkedBitmap = addWatermark(imageBitmap);
mImageView.setImageBitmap(watermarkedBitmap);
}
}
private Bitmap addWatermark(Bitmap source) {
int w = source.getWidth();
int h = source.getHeight();
Bitmap result = Bitmap.createBitmap(w, h, source.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(source, 0, 0, null);
// 设置水印图片
Bitmap watermark = BitmapFactory.decodeResource(getResources(), R.drawable.watermark);
// 计算水印大小
int watermarkWidth = (int) (w * 0.3);
int watermarkHeight = (int) (watermarkWidth * watermark.getHeight() / watermark.getWidth());
// 缩放水印图片
watermark = Bitmap.createScaledBitmap(watermark, watermarkWidth, watermarkHeight, false);
// 添加水印
canvas.drawBitmap(watermark, w - watermarkWidth - 10, h - watermarkHeight - 10, null);
return result;
}
}
```
在这个示例中,当用户点击“拍照”按钮时,调用 `dispatchTakePictureIntent()` 方法启动系统相机应用程序,用户拍照后将得到的图片作为返回值传递回来。然后,我们调用 `addWatermark()` 方法向图像中添加水印。在这个方法中,我们可以先计算出水印的大小,然后缩放水印图片并将其添加到图片的右下角。最后,我们返回一个包含水印的新位图。
阅读全文