将位图保存到Android中的文件中

时间:2014-02-27 19:02:10

标签: java android file bitmap

我有一个DrawingView类,它实现了绘制方法。当我画一些东西时,它完美地工作,但之后,当我尝试保存我在jpg文件中绘制的内容时,我得到一个黑色图像。我已经在stackoverflow中找到了很多答案,并且博客解释了如何做到这一点,并且不明白为什么我仍然有黑色图像。这是我的代码:

DrawingView:

public class DrawingView extends View {
    private Path drawPath;
    private Paint drawPaint;
    private Paint canvasPaint;
    private Canvas drawCanvas;
    private Bitmap canvasBitmap;

    public DrawingView(Context context, AttributeSet attrs) {
        super(context, attrs);

        drawPath = new Path();
        drawPaint = new Paint();
        canvasPaint = new Paint(Paint.DITHER_FLAG);

        drawPaint.setColor(Color.BLACK);
        drawPaint.setAntiAlias(true);
        drawPaint.setStrokeWidth(5f);
        drawPaint.setStyle(Paint.Style.STROKE);
        drawPaint.setStrokeJoin(Paint.Join.ROUND);
        drawPaint.setStrokeCap(Paint.Cap.ROUND);
    }

    public DrawingView(Context context) {
        super(context);

        drawPath = new Path();
        drawPaint = new Paint();
        drawPaint.setColor(Color.BLACK);
        drawPaint.setAntiAlias(true);
        drawPaint.setStrokeWidth(5f);
        drawPaint.setStyle(Paint.Style.STROKE);
        drawPaint.setStrokeJoin(Paint.Join.ROUND);
        drawPaint.setStrokeCap(Paint.Cap.ROUND);
    }

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

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(0xFFFFFF);
        canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
        canvas.drawPath(drawPath, drawPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float touchX = event.getX();
        float touchY = event.getY();

        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:
            drawCanvas.drawPath(drawPath, drawPaint);
            drawPath.reset();
            break;

        default:
            return false;
        }

        invalidate();

        return true;
    }
}

我在这里使用:

public void btFirma_FRAGMENT_CIERRE(View v) {
    final DrawingView dv = new DrawingView(this);

    LayoutParams params = CierreFragment.getdvFirma().getLayoutParams();

    dv.setLayoutParams(params);
    dv.setDrawingCacheEnabled(true);
    dv.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    dv.layout(0, 0, v.getWidth(), v.getHeight());
    dv.buildDrawingCache(true);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(dv);
    builder.setPositiveButton("Aceptar", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Log.d("DialogFirma", "Se pulsa el botón aceptar del dialog");

            // TODO Establecer el nombre que se quiere asignar a la firma.
            imageName = "prueba.jpg";

            // TODO Guardar imagen de la firma en la carpeta /FIRMAS/
            saveImageSign(dv.getDrawingCache());

            Drawable background = getImageSign(imageName);

            if (background != null)
                CierreFragment.setdvBackGround(background);
        }
    });
    builder.setNegativeButton("Cancelar", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            Log.d("DialogFirma", "Se pulsa el botón cancelar del dialog");
        }
    });

    builder.show();

}
private void saveImageSign(Bitmap finalBitmap) {
    File file = new File(
            ((AISApplication) getApplicationContext())
                    .getLocalFolderFIRMAS() + imageName);
    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();
    }
}

private Drawable getImageSign(String imageName) {
    FileInputStream in;
    try {
        in = new FileInputStream(new File(
                ((AISApplication) getApplication()).getLocalFolderFIRMAS()
                        + imageName));

        Bitmap bmp = BitmapFactory.decodeStream(in);

        return new BitmapDrawable(getResources(), bmp);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

谁能告诉我哪里失败了?

1 个答案:

答案 0 :(得分:0)

我没有深入研究你的代码,但这是我如何得到我刚刚绘制的图像:

private Bitmap getImage() {
 tile = Bitmap.createBitmap(faces[0]);      // create the bitmap (from existing or blank)         
 Canvas c = new Canvas(tile);               // create a new canvas using that bitmap
 c.drawBitmap(tile, 0, 0, null);            // draw the bitmap onto the canvas
                                            // do more drawing - here I add another image
 c.drawBitmap(scoresBm[initScores[0]], vertex.get(0).x, vertex.get(0).y, null);

 return tile;                               // just return the bitmap
}

保存图像

// write the image back out (using compression in this one)

try {
     FileOutputStream out = new FileOutputStream(imgFile);
    _bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 50, out);
     out.flush();
     out.close();
    } catch (Exception e) {