【问题标题】:how to save image to file android custom view?如何将图像保存到文件android自定义视图?
【发布时间】:2015-01-16 09:49:38
【问题描述】:

我有一个问题。

我尝试将画布图像保存到文件中

这是我的工作方式。 1.用位图创建画布对象(表单图像) 2.在画布上打印文本(使用drawText) 3.用bitmap.compress()方法保存

但它只保存了原始位图(没有文字)

我想知道如何将文本打印的位图保存到文件中? 这是我的代码

protected class MyView extends View{

    public MyView(Context context){
        super(context);
    }

    public void onDraw(Canvas canvas){
        Paint pnt = new Paint();
        pnt.setColor(Color.BLACK);
        canvas.scale(0.5f,0.5f);
        Resources res = getResources();
        BitmapDrawable bd =(BitmapDrawable)res.getDrawable(R.drawable.hanhwa);
        Bitmap bit = bd.getBitmap();
        canvas.drawBitmap(bit,0,0,null);

        pnt.setTextSize(30);
        canvas.drawText("hello",290,340,pnt);
        canvas.restore();


        //file save//
        File folder = new File(Environment.getExternalStorageDirectory()+"/DCIM/tmp");

        boolean isExist = true;
        if(!folder.exists()){
            isExist = folder.mkdir();
        }
        if(isExist){
            File file = null;
            boolean isFileExist = false ;
            file = new File(folder.getPath() + "/tmp.jpg");

            if(file != null && !file.exists()){
                try{
                    isFileExist = file.createNewFile();
                } catch(IOException e){
                    e.printStackTrace();
                }
            }
            else{
            }

            if(file.exists()){
                FileOutputStream fos = null;
                try{
                    fos = new FileOutputStream(file);

                    bit.compress(Bitmap.CompressFormat.JPEG,100,fos);
                }
                catch(Exception e){
                    e.printStackTrace();
                }
                finally{
                    try{
                        fos.close();
                    }
                    catch(IOException e){
                        e.printStackTrace();
                    }
                }

            }
        }
        else{
            //Toast.makeText(MyView.this,"foler not exist.",Toast.LENGTH_LONG).show();
        }
    }
}

【问题讨论】:

    标签: android canvas bitmap


    【解决方案1】:
    Bitmap.compresss()
    

    此方法将位图的压缩版本写入指定的输出流。

    将位图实例传递给画布

    这是伪代码。 (除了其他语句,例如try-catch,语句)

    1. 画布 c = 新画布(位);
    2. c.drawText("hello",290,340,pnt);
    3. b.compress(Bitmap.CompressFormat.JPEG, 100, fos);

    this post 也会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多