Preface
Recently, there is an electronic signature function in the project, which requires the customer's handwritten signature and then saves it locally and uploads it to the cloud.
//获取bitmap
Bitmap bitmapFromView = mSignatureView.getBitmapFromView();
BitmapUtil.saveImageToGallery(this, bitmapFromView);
压缩为JPEG格式
I have modified the saveImageToGallery method that was used beforeBitmap.CompressFormat.JPEG
压缩为WEBP无损格式
The core modification content is to modify the format of the compressed image of bitmapBitmap.CompressFormat.WEBP_LOSSLESS
View the source code and you can see the CompressFormat enumeration class
public enum CompressFormat {
/**
* 压缩为JPEG格式
* 压缩到最小尺寸
*/
JPEG (0),
/**
*压缩为PNG格式。
*/
PNG (1),
/**
*压缩为WEBP格式。
*/
WEBP (2),
/**
*压缩为WEBP有损格式
*/
WEBP_LOSSY (3),
/**
*压缩为WEBP无损格式。
*/
WEBP_LOSSLESS (4);
CompressFormat(int nativeInt) {
this.nativeInt = nativeInt;
}
final int nativeInt;
}
save local
To save the bitmap locally, you need to generate a new directory. If there is no directory, create a new folder
Then change the bitmap image generation format to
bmp.compress(Bitmap.CompressFormat.WEBP_LOSSLESS, 100, fos);
Finally refresh the album< /span>
MediaScannerConnection.scanFile
/**
* 保存图片到相册
*
* @param context 应用程序上下文
* @param bmp 需要保存的 bitmap
*/
public static void saveImageToGallery(Context context, Bitmap bmp) {
File appDir = new File(Environment.getExternalStorageDirectory(), "Pictures");
if (!appDir.exists()) {
appDir.mkdirs();
}
String fileName = "photo_" + System.currentTimeMillis() + ".png";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.WEBP_LOSSLESS, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(context,
new String[]{
file.toString()}, null, null);
}
Solve the background black
Use canvas to change the background color of the bitmap generated by taking a photo or handwritten electronic signature.
Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(bitmap, 0, 0, null);