代码之家  ›  专栏  ›  技术社区  ›  d-man

画布上的图像到jpeg文件

  •  25
  • d-man  · 技术社区  · 15 年前

    我在画布上画二维图像。

    我想把画布上显示的图像保存到jpeg文件中,我该怎么做?

    3 回复  |  直到 9 年前
        1
  •  25
  •   Samuh    15 年前
    1. 创建空位图
    2. 创建一个新的画布对象并将此位图传递给它
    3. 调用view.draw(canvas)将刚刚创建的canvas对象传递给它。 Refer Documentation of method for details.
    4. 使用bitmap.compress()将位图的内容写入输出流,可能是文件。

    伪代码:

    Bitmap  bitmap = Bitmap.createBitmap( view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas); 
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); 
    
        2
  •  11
  •   Arun    13 年前
    1. 设置图形缓存已启用
    2. 想画什么就画什么
    3. 从视图中获取位图对象
    4. 压缩并保存图像文件
    
    import java.io.File;
    import java.io.FileOutputStream;
    
    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    
    public class CanvasTest extends Activity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            Draw2d d = new Draw2d(this);
            setContentView(d);
        }
    
        public class Draw2d extends View {
    
            public Draw2d(Context context) {
                super(context);
                setDrawingCacheEnabled(true);
            }
    
            @Override
            protected void onDraw(Canvas c) {
                Paint paint = new Paint();
                paint.setColor(Color.RED);          
                c.drawCircle(50, 50, 30, paint);
    
                try {
                    getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/mnt/sdcard/arun.jpg")));
                } catch (Exception e) {
                    Log.e("Error--------->", e.toString());
                }
                super.onDraw(c);
            }
    
        }
    
    }
        3
  •  6
  •   Harry    12 年前

    帆布到JPG:

    Canvas canvas = null;
    FileOutputStream fos = null;
    Bitmap bmpBase = null;
    
    bmpBase = Bitmap.createBitmap(image_width, image_height, Bitmap.Config.ARGB_8888);
    canvas = new Canvas(bmpBase);
    // draw what ever you want canvas.draw...
    
    // Save Bitmap to File
    try
    {
        fos = new FileOutputStream(your_path);
        bmpBase.compress(Bitmap.CompressFormat.PNG, 100, fos);
    
        fos.flush();
        fos.close();
        fos = null;
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        if (fos != null)
        {
            try
            {
                fos.close();
                fos = null;
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }