失去位图图像质量

时间:2019-08-14 04:45:33

标签: java android bitmap

我正在从图库中获取图像进入布​​局,然后使用getBitmap()获得该布局的位图,获得位图后,我将使用saveImage()将图像保存到设备存储中。 / p>

获取位图并保存位图后,该位图的质量和像素降低太多,如图所示Saved imageOrignal image

这是获取和保存位图的代码

private Bitmap getBitmap(View v) {
    v.clearFocus();
    v.setPressed(false);

    boolean willNotCache = v.willNotCacheDrawing();
    v.setWillNotCacheDrawing(false);


    int color = v.getDrawingCacheBackgroundColor();
    v.setDrawingCacheBackgroundColor(0);

    if (color != 0) {
        v.destroyDrawingCache();
    }
    v.buildDrawingCache();
    Bitmap cacheBitmap = v.getDrawingCache();
    if (cacheBitmap == null) {
        Toast.makeText(this, "Something Wrong", Toast.LENGTH_SHORT).show();
        return null;
    }

    Bitmap lastimage = Bitmap.createBitmap(cacheBitmap);

    v.destroyDrawingCache();
    v.setWillNotCacheDrawing(willNotCache);
    v.setDrawingCacheBackgroundColor(color);

    //2048x2048 resolution
    int newWidth = 2048;
    int newHeight = 2048;

    int width = lastimage.getWidth();
    int height = lastimage.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;

    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    Bitmap resizedBitmap = Bitmap.createBitmap(lastimage, 0, 0, width, height, matrix, true);
    lastimage.recycle();

    saveImage(resizedBitmap);

    return resizedBitmap;

}

保存:

 private void saveImage (Bitmap finalBitmap) {
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/NewFolder");
    myDir.mkdirs();
    String fname = "Image-.png";
    File file = new File(myDir, fname);
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

感谢任何人的帮助。

0 个答案:

没有答案