将图像从图像视图保存到设备

时间:2019-04-03 13:06:51

标签: java android

我在布局中有两个Image-View,一个在背景中,另一个在其上方(在前景),我想保存两个图像。因此,谁能帮助我,如何将两个图像都保存为设备图像。

谢谢。

1 个答案:

答案 0 :(得分:1)

我发现here的一个简单解决方案是将两个imageView放在一个Layout中,然后将布局保存为位图。我将在此处重新输入解决方案代码

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

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

// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);

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

Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);

return bitmap;

}

现在有了位图,您可以像这样将其保存到存储中

  private void saveImage(Bitmap finalBitmap, String image_name) {

    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root);
    myDir.mkdirs();
    String fname = "Image-" + image_name+ ".jpg";
    File file = new File(myDir, fname);
    if (file.exists()) file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

别忘了在manifest file

中添加权限
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />