在Android中将画布保存为图像

时间:2017-06-10 07:34:01

标签: android canvas

我从DrawingView扩展了类View并在其上绘制路径一切正常 但是当我尝试将画布保存为图像时,它无效。

这是我正在尝试的代码。

// drawView is an object of DrawingView class
drawView.setDrawingCacheEnabled(true);
                String imgSaved = MediaStore.Images.Media.insertImage(
                        getContentResolver(), drawView.getDrawingCache(),
                        UUID.randomUUID().toString()+".png", "drawing");
                if(imgSaved!=null){
                    Toast savedToast = Toast.makeText(getApplicationContext(),
                            "Drawing saved to Gallery!", Toast.LENGTH_SHORT);
                    savedToast.show();
                }
                else{
                    Toast unsavedToast = Toast.makeText(getApplicationContext(),
                            "Oops! Image could not be saved.", Toast.LENGTH_SHORT);
                    unsavedToast.show();
                }
                drawView.destroyDrawingCache();

我一直在收到消息Oops! Image could not be saved.这段代码有什么问题,为什么不保存呢?

4 个答案:

答案 0 :(得分:1)

保存到图库需要WRITE_EXTERNAL_STORAGE权限。如果在您的清单中声明,如果您的应用针对API 23 +

,您仍需要在Android M及更高版本上申请

答案 1 :(得分:1)

回答来自Stackoverflow Answer

但需要进行细微更改,例如file.seperator法术错误ile.separator更改且try阻止。{/ p>

只需使用content

更改drawView即可

最终守则:

try {
    drawView.setDrawingCacheEnabled(true);
    Bitmap bitmap = drawView.getDrawingCache();
    File f = null;
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
         File file = new File(Environment.getExternalStorageDirectory(),"TTImages_cache");
         if(!file.exists()){
             file.mkdirs();
         }
         f = new File(file.getAbsolutePath()+file.separator+ "filename"+".png");
    }
    FileOutputStream ostream = new FileOutputStream(f);
    bitmap.compress(Bitmap.CompressFormat.PNG, 10, ostream);
    ostream.close();
} catch(Exception e){
    e.printStackTrace();
}

答案 2 :(得分:0)

  

您可以尝试以下代码   首先,您必须通过获取高度和宽度将整个布局转换为位图。

if (mBitmap == null) {
                    mBitmap = Bitmap.createBitmap(mContent.getWidth(),
                            mContent.getHeight(), Bitmap.Config.RGB_565);
                    ;
                }
  

然后保存到画布

            Canvas canvas = new Canvas(mBitmap);
            try {
                FileOutputStream mFileOutStream = new FileOutputStream(mypath);

            v.draw(canvas);
  

最后在特定地方的png或jpg商店

            mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);

            mFileOutStream.flush();
            mFileOutStream.close();
            String url = Images.Media.insertImage(getContentResolver(),
                    mBitmap, "title", null);
            Log.v("log_tag", "url: " + url);
  

我希望这会对你有所帮助:D

答案 3 :(得分:0)

首先,您必须将签名视图转换为位图,如下所示:

    public Bitmap takeScreenShot(View view) {
    // configuramos para que la view almacene la cache en una imagen
    view.setDrawingCacheEnabled(true);
    view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
    view.buildDrawingCache();
    if (view.getDrawingCache() == null) return null; // Verificamos antes de que no sea null
    // utilizamos esa cache, para crear el bitmap que tendra la imagen de la view actual
    Bitmap snapshot = Bitmap.createBitmap(view.getDrawingCache());
    view.setDrawingCacheEnabled(false);
    view.destroyDrawingCache();
    return snapshot;
}

现在将此方法称为新的位图,

  Bitmap newbitmap = takeScreenShot(signatureview);
  save(newbitmap);

对于保存此位图,请调用此方法:

   private void save(Bitmap finalBitmap) {
    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    System.out.println(root + " Root value in saveImage Function");
    File myDir = new File(root + "/Canavsdemo");

    if (!myDir.exists()) {
        myDir.mkdirs();
    }

    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String iname = "filter_" + n + ".jpg";
    File file = new File(myDir, iname);
    if (file.exists())
        file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
        Toast.makeText(getApplicationContext(),
                "Saved Sucessfully",
                Toast.LENGTH_LONG).show();

    } catch (Exception e) {
        e.printStackTrace();
    }

    MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });

    String Image_path = Environment.getExternalStorageDirectory() + "/Pictures/CameraFilter/" + iname;
    File[] files = myDir.listFiles();
    int numberOfImages = files.length;
    System.out.println("Total images in Folder " + numberOfImages);
}