将片段制作成图像文件并将其保存到手机的内部硬盘上

时间:2017-10-03 12:41:00

标签: android android-bitmap fileoutputstream

我想为png文件创建一个片段并将其保存在设备上。但我不明白如何将文件保存到设备内部存储。我得到异常" FileNotFoundException e"当我尝试这个程序时。

Button save = (Button) findViewById(R.id.save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                View fragment = (View) findViewById(R.id.fragment2);
                viewToBitmap(fragment);
            }
        }
        );
    }

    public Bitmap viewToBitmap(View view) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        try {
            FileOutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/path/to/file.png");

            bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
            output.close();
        } catch (FileNotFoundException e) {
            Toast.makeText(this, "Error1", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (IOException e) {
            Toast.makeText(this, "Error2", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        return bitmap;
    }

1 个答案:

答案 0 :(得分:0)

您正在创建FileOutputStream,但在此之前尚未创建File。在将输出流写入该文件之前,需要创建FileFolder和File。更正了以下代码viewToBitmap

的代码
public Bitmap viewToBitmap(View view) {
                Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(bitmap);
                view.draw(canvas);
                try {
                File tempFolder = new File(Environment.getExternalStorageDirectory() + "/path/to");
                if (!tempFolder.exists()) tempFolder.mkdirs();
                File tempFile = File.createTempFile("tempFile", ".jpg", tempFolder);
                        FileOutputStream output = new FileOutputStream(tempFile);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
                        output.close();
                } catch (FileNotFoundException e) {
                    Toast.makeText(this, "Error1", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                } catch (IOException e) {
                    Toast.makeText(this, "Error2", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
                return bitmap;
            }