2010-02-01 63 views
23

我在畫布上繪製2D圖像。畫布上的圖像JPEG文件

我想將畫布上顯示的圖像保存爲JPEG文件,我該怎麼做?

+0

既然你提到的鏈接長久以來是死的,你也許可以添加更多的上下文連接到問題本身? – Flexo 2015-05-22 14:49:39

回答

23
  1. 創建一個空的位圖
  2. 創建一個新的Canvas對象和該位圖傳遞給它
  3. 呼叫view.draw(Canvas)的傳遞您剛纔創建的畫布對象。 Refer Documentation of method for details.
  4. 使用Bitmap.compress()將位圖的內容寫入OutputStream文件中。

僞代碼:

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); 
+11

你好Samuh, 我試過了代碼,它會生成一個jpeg文件,但沒有畫布繪製的形狀或我曾經寫在畫布上。 有任何意見。 感謝, 科坦 – 2011-02-09 09:50:21

+0

感謝您的回答。 – 2011-11-21 04:34:01

12
  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); 
     } 

    } 

}
+7

不知何故,在onDraw方法中壓縮並保存是個不好的主意。 – 2013-06-23 18:10:28

+0

它給了我空指針異常 – abh22ishek 2016-01-14 12:58:15

6

畫布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(); 
     } 
    } 
}