안드로이드 비트맵에 저장된 로컬 배경이 검은색이고 아무것도 선명하게 보이지 않는 문제에 대한 해결 방법

머리말

최근 프로젝트에는 고객의 자필 서명을 요구한 후 이를 로컬에 저장하고 클라우드에 업로드하는 전자 서명 기능이 있습니다.

 //获取bitmap
  Bitmap bitmapFromView = mSignatureView.getBitmapFromView();
  BitmapUtil.saveImageToGallery(this, bitmapFromView);

压缩为JPEG格式
이전에 사용했던 saveImageToGallery 메소드를 수정했습니다.Bitmap.CompressFormat.JPEG

压缩为WEBP无损格式
수정의 핵심 내용은 비트맵의 압축된 이미지 형식을 수정하는 것입니다.Bitmap.CompressFormat.WEBP_LOSSLESS

소스 코드를 보면 CompressFormat 열거형 클래스를 볼 수 있습니다.

 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;
    }

로컬 저장

비트맵을 로컬에 저장하려면 새 디렉터리를 생성해야 합니다. 디렉터리가 없으면 새 폴더를 생성하세요.
그런 다음 비트맵 이미지 생성 형식을 로 변경하세요.
bmp.compress(Bitmap.CompressFormat.WEBP_LOSSLESS, 100, fos);
마지막으로 앨범 새로고침
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);
    }

검은색 배경 해결

사진 촬영이나 자필 전자 서명을 통해 생성된 비트맵의 배경색을 캔버스를 사용하여 변경할 수 있습니다.

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);

효과를 얻다

1

추천

출처blog.csdn.net/Life_s/article/details/134933581