1

我尝试了几个代码来将我的自定义视图保存为 .jpg 格式。我正在将视图转换为位图,然后将其保存,如下所示。但每次尝试保存的图像大小始终为 0 Kb,并且文件不包含任何内容。我已经提出以下许可。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

这是我使用的代码之一;

drawView.setDrawingCacheEnabled(true);
drawView.buildDrawingCache();
Bitmap b = drawView.getDrawingCache();
 private void SaveImage(Bitmap finalBitmap) {

      String root = Environment.getExternalStorageDirectory().toString();
      File myDir = new File(root + "/saved_images");    
      myDir.mkdirs();
      String fname = "Image.jpg";
      File file = new File (myDir, fname);
      if (file.exists ()) file.delete (); 
        try {
           FileOutputStream out = new FileOutputStream(file);
           finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

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

我还想明确指出,这段代码的主要思想不是来自我。

整个完整的代码;公共类 DrawPad 扩展视图 {

//drawing path
    private Path drawPath;
    //drawing and canvas paint
    private Paint drawPaint, canvasPaint;
    //initial color
    private int paintColor =0xff000000;
    //canvas
    private Canvas drawCanvas;
    //canvas bitmap
    private Bitmap canvasBitmap;

    //erase flag
    private boolean erase=false;

    public DrawPad(Context context, AttributeSet attrs){
        super(context, attrs);
        setupDrawing();


    }
    public Paint getPaint(){
        return drawPaint;
    }
    //setup drawing
    private void setupDrawing(){

        //prepare for drawing and setup paint stroke properties

        drawPath = new Path();
        drawPaint = new Paint();
        drawPaint.setColor(paintColor);
        drawPaint.setAntiAlias(true);
        drawPaint.setStrokeWidth(1.0f);
        drawPaint.setStyle(Paint.Style.STROKE);
        drawPaint.setStrokeJoin(Paint.Join.ROUND);
        drawPaint.setStrokeCap(Paint.Cap.ROUND);
        canvasPaint = new Paint(Paint.DITHER_FLAG);

    }
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        drawCanvas = new Canvas(canvasBitmap);
    }

    //draw the view - will be called after touch event
    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
        canvas.drawPath(drawPath, drawPaint);
    }

    //register user touches as drawing action
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float touchX = event.getX();
        float touchY = event.getY();
        //respond to down, move and up events
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            drawPath.moveTo(touchX, touchY);
            break;
        case MotionEvent.ACTION_MOVE:
            drawPath.lineTo(touchX, touchY);
            break;
        case MotionEvent.ACTION_UP:
            drawPath.lineTo(touchX, touchY);
            drawCanvas.drawPath(drawPath, drawPaint);
            drawPath.reset();
            break;
        default:
            return false;
        }
        //redraw
        invalidate();
        return true;

    }

    //update color
    public void setColor(String newColor){
        invalidate();
        paintColor = Color.parseColor(newColor);
        drawPaint.setColor(paintColor);
    }

    //set erase true or false
    public void setErase(boolean isErase){
        erase=isErase;

        if(erase){ 
            drawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
            drawPaint.setStrokeWidth(15.0f);
        }
        else {
            drawPaint.setStrokeWidth(1.0f);
            drawPaint.setXfermode(null);
        }
    }

    //start new drawing
    public void startNew(){
        drawCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
        drawPaint.setStrokeWidth(1.0f);
        invalidate();
    }
    public void SaveImage(Bitmap finalBitmap,String spin) {
        if(finalBitmap == null) {
            Toast unsavedToast = Toast.makeText(getContext(), 
                    "Oops! Page could not be saved.", Toast.LENGTH_SHORT);
            unsavedToast.show();
            }

          this.setDrawingCacheEnabled(true);
          this.buildDrawingCache();
          finalBitmap=this.getDrawingCache();
          String root = Environment.getExternalStorageDirectory().toString();
          File myDir = new File(root + "/answers");    
          myDir.mkdirs();
          String fname = spin+".jpg";
          File file = new File (myDir, fname);
          if (file.exists ()) file.delete (); 
            try {
               FileOutputStream out = new FileOutputStream(file);
              if ( finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)==true){
               out.flush();
               out.close();
              }
              if(finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)==false){
                Toast fToast = Toast.makeText(getContext(), 
                        "compression failed", Toast.LENGTH_SHORT);
                fToast.show();
              }

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

2 回答 2

1

检查返回值finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);

文档说,如果成功压缩到指定的流,该方法将返回 true 。我敢打赌它会为你返回假。

检查您要压缩的位图中的内容。它似乎是空的,或者它有什么问题。查找创建位图的位置并检查每个步骤是否成功。就像finalBitmap.compress在成功/失败时返回真/假一样,从创建点开始检查位图上的每个操作,因为看起来某处出现了问题。

如果您仍然无法弄清楚,请在您的帖子中添加所有在进入您的方法finalBitmap之前操作的代码。SaveImage(Java 中的 btw 方法应该以小写字母开头,例如saveImage.)

于 2013-10-08T06:13:45.977 回答
0

也许您的位图等于空值。你能检查你的位图吗?

于 2013-10-08T05:36:19.840 回答