简体   繁体   中英

Saving a Bitmap into a file in Android

I have a DrawingView class, which implements painting methods. It works perfectly when I paint something, but after, by the time I try to save what I've painted in a jpg file I get a black image. I've read many answers here in Stack Overflow, and blogs which explain how to do that, and don't understand why I still having the black image. Here is my code:

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

And I'm using here:

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

Can anyone tell me where's my fail?

I haven't looked too deeply into your code, but here's how I get the image I've just drawn:

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
}

Saving the image

// 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) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM