2010-02-01 4 views
23

캔버스에 2D 이미지를 그립니다.캔버스에서 JPEG 파일로의 이미지

캔버스에 표시된 이미지를 JPEG 파일로 저장하고 싶습니다. 어떻게해야합니까?

+0

당신이 언급 된 링크는 아마 질문 자체에 좀 더 컨텍스트를 추가 할 수 있습니다 긴 죽은 이후이기 때문에? – Flexo

답변

23
  1. 새로운 캔버스 객체를 생성하고 당신이 방금 만든 캔버스 객체를 전달 그것을
  2. 전화 view.draw (캔버스)이 비트 맵을 통과 빈 비트 맵을 만들 수 있습니다. Refer Documentation of method for details.
  3. 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 파일을 생성하지만 캔버스 그려진 모양이 없거나 캔버스에 작성한 내용이 없습니다. 모든 의견. 감사합니다, 답변을 케탄 –

+0

감사합니다. –

12
  1. 설정 그리기 캐시는
  2. 보기
  3. 압축에서 비트 맵 오브젝트를 취득하고 이미지 파일을 저장 원하는
  4. 그리기를 사용
  5. JPG210

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 메서드 내에서 압축하고 저장하는 것은 좋지 않은 생각입니다. –

+0

그것은 나에게 널 포인터 예외를 준다. – abh22ishek

6

캔버스 :

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