如何在位图中存储来自 imageView 的背景图像?

How to store background image from imageView in bitmap?

我正在尝试将 imageView 中的图像存储在位图中,以便我可以将其存储在 android 设备的图库中。每次保存图像时,都不会存储 imageView 的背景。我错过了什么?

这是我的代码:

ImageView imageView = (ImageView) findViewById(R.id.img);
imageView.setBackgroundResource(R.drawable.img1);
BitmapDrawable draw = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = draw.getBitmap();

将图像存储到图库中的代码是:

FileOutputStream outStream = null;
            File dir = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "MyAlbum");
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    Log.d("MyAlbum", "failed to create directory");
                    Toast.makeText(MainActivity.this, "Failed to make directory", Toast.LENGTH_SHORT).show();
                }
            }
            String fileName = String.format("%d.jpg", System.currentTimeMillis());
            File outFile = new File(dir, fileName);
            try {
                outStream = new FileOutputStream(outFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                outStream.flush();
                outStream.close();

                Toast.makeText(getApplicationContext(), "PICTURE SAVED", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                intent.setData(Uri.fromFile(dir));
                sendBroadcast(intent);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

你可以试试这个,

private void saveImageToStorage(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();
        Log.i("LOAD", root + fname);
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

编码愉快:-)

在这种情况下,您可以截取此视图 (ImageView) 的屏幕截图,它会简单地获取此时在此视图上绘制的内容,并将其转换为可以保存的位图。

答案已被提及here

神奇的地方在于

ImageView yourImageView = .. // Get reference it to your view.
yourImageView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(yourImageView.getDrawingCache());
yourImageView.setDrawingCacheEnabled(false);

Ta-da 你可以使用你的快照 btimap