Bitmap does not save only black image

I'm trying to save a custom view as an image, but it doesn't, it only gives a black image when I open it in my android device gallery. The custom view looks like this

public class page extends View  
{
    private static final String TAG = "DrawView";

private boolean clearflag = false;
private static final float MINP = 0.25f;
private static final float MAXP = 0.75f;

private Context context;
private Paint mPaint = new Paint();
private int[] pencolor = { Color.BLUE, Color.GREEN, Color.MAGENTA,
          Color.BLACK, Color.CYAN, Color.GRAY, Color.RED, Color.DKGRAY,
          Color.LTGRAY, Color.YELLOW };

private Canvas  mCanvas;
private Path    mPath;

private ArrayList<Path> paths = new ArrayList<Path>();


public void ClearScreen()
{
    clearflag = true;
    invalidate();
}
public void resetPenColor()
{
    Random random = new Random();
    random.setSeed(System.currentTimeMillis());

    int color_index = random.nextInt(pencolor.length);
   //   Toast.makeText(context, "Pen Color "+color_index, Toast.LENGTH_SHORT).show();
    mPaint.setColor(pencolor[color_index]);
}

public void init(Context context) {
    //super(context);
    this.context = context;
    setFocusable(true);
    setFocusableInTouchMode(true);

   //this.setOnTouchListener(this);

    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(Color.BLACK);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(6);
    mCanvas = new Canvas();
    mPath = new Path();
    paths.add(mPath);


}



public page(Context context, AttributeSet attrs)
{
    super(context, attrs);
    init(context);
    this.context = context;
}

public page(Context context, AttributeSet attrs, int defStyle) 
{
    super(context, attrs, defStyle);
    init(context);
    this.context = context;

}
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onDraw(Canvas canvas) 
    {            

        if(clearflag)
        {
            canvas.drawColor(Color.WHITE);
            clearflag = false;
            paths.clear();
            paths.add(mPath);
            Log.v("Clear Screen", "---");
        }
        else
        {
            for (Path p : paths)
            {
                canvas.drawPath(p, mPaint);  
                Log.v("draw", "---line");
            }
        }
    }

    private float mX, mY;
    private static final float TOUCH_TOLERANCE = 4;

    private void touch_start(float x, float y) 
    {
        mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
        Log.v("Touch", "Start");
    }
    private void touch_move(float x, float y) 
    {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) 
        {
            mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
            mX = x;
            mY = y;
        }
        Log.v("Touch", "Move");
    }
    private void touch_up() 
    {
        mPath.lineTo(mX, mY);
        // commit the path to our offscreen
        mCanvas.drawPath(mPath, mPaint);
        // kill this so we don't double draw            
        mPath = new Path();
        paths.add(mPath);

        Log.v("Touch", "Move");
    }


@Override
public boolean onTouchEvent(MotionEvent event) 
{

     super.onTouchEvent(event);
     float x = event.getX();
      float y = event.getY();

      switch (event.getActionMasked()) 
      {
          case MotionEvent.ACTION_DOWN:
              touch_start(x, y);
              invalidate();
              break;
          case MotionEvent.ACTION_MOVE:
              touch_move(x, y);
              invalidate();
              break;
          case MotionEvent.ACTION_UP:
              touch_up();
              invalidate();
              break;
          case MotionEvent.ACTION_POINTER_DOWN:
              resetPenColor();
            //  Toast.makeText(context, "Multitouch", Toast.LENGTH_SHORT).show();
              invalidate();
              break;
      }
      return true;
}

      

}

and the main activity where I save the bitmap is like this

public class Book extends Activity
{
    private ImageButton refresh;
    private ImageButton save;
    private page pg;

    public void init()
    {
        refresh = (ImageButton) findViewById(R.id.refresh);
        save = (ImageButton) findViewById(R.id.save);
        pg = (page) findViewById(R.id.page);
    }

    public void onCreate(Bundle onsavestate)
    {
        super.onCreate(onsavestate);
        setContentView(R.layout.book);

        init();
        addListeners();

    }



    public void addListeners()
    {
        refresh.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View arg0) 
            {
                // TODO Auto-generated method stub
                pg.ClearScreen();
            }

        });

        save.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v) 
            {
                // TODO Auto-generated method stub  
                saveautograph();
            }

        }); 
    }

    public void saveautograph()
    {
        Bitmap returnedbitmap = Bitmap.createBitmap(pg.getWidth(), pg.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedbitmap);
        pg.draw(canvas);
        /*Drawable bgDrawable = pg.getBackground();
        if(bgDrawable != null)
        {
            bgDrawable.draw(canvas);
        }*/

        OutputStream stream = null;
        try 
        {
            stream = new FileOutputStream(Environment.getExternalStorageDirectory()+"/autograph.jpeg");
        } 
        catch (FileNotFoundException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         try 
         {
            stream.flush();
            stream.close();
        } 
         catch (IOException e) 
         {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if(stream == null) 
        {
            Log.v("Stream", "null");
        }
        if(returnedbitmap == null)
        {
            Log.v("bitmap", "null");
        }
        returnedbitmap.compress(CompressFormat.PNG, 90, stream);
    }



    }

      

and here is the xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <LinearLayout
        android:id="@+id/buttonlayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@drawable/buttoncontainer"
        android:gravity="bottom|center"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/refresh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@color/white"
            android:src="@drawable/refresh"
            android:layout_marginLeft="4dp" />

        <ImageButton
            android:id="@+id/save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@color/white"
            android:src="@drawable/save"
            android:layout_marginLeft="4dp"
            android:layout_marginRight="4dp" />
    </LinearLayout>


    <com.gsmappstabs.autographplease.page
        android:id="@+id/page"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/buttonlayout" />

</RelativeLayout>

      

help me please

+1


source to share


2 answers


Update your method saveautograph

like this:

public void saveautograph()
{
    pg.setDrawingCacheEnabled(true);
    pg.buildDrawingCache();
    Bitmap returnedBitmap = pg.getDrawingCache();
    try {
           FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory()+"/autograph.jpeg");
           returnedBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
           out.close();
    } catch (Exception e) {
           e.printStackTrace();
    }
    pg.setDrawingCacheEnabled(false);
}

      



Basically, you can get the bitmap representation using the method getDrawingCache

. Then directly save the file bitmap

to a file.

+1


source


I believe you are trying to save the captions captured as an image. I have something ready-made that I reuse in my projects.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.leelasofttech.android.pcm.R;
import com.leelasofttech.android.pcm.util.Constants;

public class DrawView extends View {

protected static final String TAG = "DrawView";

protected Bitmap mBitmap;
protected Canvas mCanvas;
protected Path mPath;
protected Paint mBitmapPaint;
protected Paint paint;
protected int bgColor;

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

    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    bgColor = context.getResources().getColor(R.color.edit_box_normal);
    setupPaint();
}

public DrawView(Context context, AttributeSet attributeSet) {
    super(context, attributeSet);

    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    bgColor = context.getResources().getColor(R.color.edit_box_normal);

    setupPaint();
}

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

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
    canvas.drawPath(mPath, getPaint());
}

private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;

private void touchStart(float x, float y) {
    mPath.reset();
    mPath.moveTo(x, y);
    mX = x;
    mY = y;
}

private void touchMove(float x, float y) {
    float dx = Math.abs(x - mX);
    float dy = Math.abs(y - mY);
    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
        mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
        mX = x;
        mY = y;
    }
}

private void touchUp() {
    mPath.lineTo(mX, mY);
    // commit the path to our offscreen
    mCanvas.drawPath(mPath, getPaint());
    // kill this so we don't double draw
    mPath.reset();
}

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

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touchStart(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touchMove(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            touchUp();
            invalidate();
            break;
    }
    return true;
}

protected void setupPaint() {
    paint = new Paint();
    paint.setAntiAlias(true);
    paint.setDither(true);
    paint.setColor(bgColor);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeJoin(Paint.Join.ROUND);
    paint.setStrokeCap(Paint.Cap.ROUND);
    paint.setStrokeWidth(4);
}

public String toJPEGFile(String folderName, String fileName) {
    File folder = new File(Environment.getExternalStorageDirectory() + File.separator + Constants.APP_FOLDER + File.separator + folderName + File.separator);
    if (!folder.exists()) {
        folder.mkdirs();
    }

    File file = null;
    try {
        this.setDrawingCacheEnabled(true);
        file = new File(folder.getPath() + File.separator + fileName + Constants.FILE_TYPE_JPEG);
        FileOutputStream fos = new FileOutputStream(file);
        Bitmap bitmap = this.getDrawingCache();
        bitmap.compress(CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
        return file.getAbsolutePath();
    }
    catch (FileNotFoundException ex) {
        Log.e(TAG, ex.getMessage(), ex);
    }
    catch (IOException ex) {
        Log.e(TAG, ex.getMessage(), ex);
    }
    catch (Exception ex) {
        Log.e(TAG, ex.getMessage(), ex);
    }
    return null;
}

public Paint getPaint() {
    return paint;
}

public void setPaint(Paint paint) {
    this.paint = paint;
}

public void changePaintStroke(float stroke) {
    paint.setStrokeWidth(stroke);
}

public void changePaintColor(int newColor) {
    paint.setColor(newColor);
}
}

      

// View signature



import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Path;
import android.util.AttributeSet;


public class SignatureView extends DrawView {

public SignatureView(Context context) {
    super(context);
    paint.setColor(Color.BLACK);
}

public SignatureView(Context context, AttributeSet attributeSet) {
    super(context, attributeSet);
    paint.setColor(Color.BLACK);
}

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

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
    canvas.drawPath(mPath, getPaint());
}

public void resetSignatures() {
    mPath = new Path();
    invalidate();
}
}

      

Hope it helps.

+1


source







All Articles