How to save canvas drawing using SurfaceView as image? - android

How to save canvas drawing using SurfaceView as image not the view.

Try below code might help
Bitmap bitmap = Bitmap.createBitmap(mSurfaceView.getWidth(), mSurfaceView.getHeight(), Bitmap.Config.ARGB_8888);
mSurfaceView.draw(new Canvas(bitmap));
try {
OutputStream out = new BufferedOutputStream(new FileOutputStream(saved.png));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
Log.w(TAG, e);
}

Related

How to get the bitmap of current layout(For sharing the screen as image) instead of taking screenshot?

How to get the bitmap of current layout(For sharing the screen as image) instead of taking screenshot? I'm getting the view of layout using following line,
I can able to get bitmap of this layout but the image is looking as empty(I got blank image). This is my code.
View cardShareView = getLayoutInflater().inflate(R.layout.activity_cad_profile, null);
boolean imageResult=saveImageInLocal(getBitmapFromView(cardShareView), "cad_share.png") == true
public static Bitmap getBitmapFromView(View view) {
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.draw(canvas);
return bitmap;
}
private boolean saveImageInLocal(Bitmap imageData, String filename) {
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/KKMC/";
File sdIconStorageDir = new File(iconsStoragePath);
//create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
filePath = sdIconStorageDir.toString() + filename;
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
//choose another format if PNG doesn't suit you
imageData.compress(Bitmap.CompressFormat.PNG, 70, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
} catch (IOException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
}
return true;
}
Advance Thanks for your response.
Expecting this image
Bit I got this image
Finally, I created duplicate layout(activity_cad_profile.xml) for take the full view as image which is loaded at the time of main layout is loading. I don't know this is correct way or not. But it's working fine for me.

Bitmap loses transparency when it's saved

i have a problem when i'm trying to save a bitmap to the external picture directory. When i use the Bitmap.compress function to save it, the bitmap loses its transparency and makes the background black. But when i pass the bitmap to a imageview and show it in the activity it looks fine and has transparency. Only when i try to save it, then transparency turns black.
I have to say, that im using two bitmaps and porterduff mode the draw a path on a bitmap and show only the picture in the drawn path, and all other pixels should be cut off or transparent.
So here's the function for creating a path bitmap:
private void createPathBitmap(RectF rect, Bitmap bitmap, Path path) {
RectF tmpRect = new RectF(rect);
Bitmap src = Bitmap.createBitmap(bitmap, (int) tmpRect.left, (int) tmpRect.top, (int) tmpRect.width(), (int) tmpRect.height());
Bitmap dst = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(dst);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(mDisplayDensity * SnippetLayer.PATH_DIAMETER);
path.offset(-rect.left, -rect.top);
canvas.drawPath(path, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
RectF srcRect = new RectF(0, 0, rect.width(), rect.height());
canvas.drawBitmap(src, null, srcRect, paint);
BitmapManager.sBitmapSnippet = dst;
}
And here's the method for saving that bitmap to external storage:
SimpleDateFormat dateFormat = new SimpleDateFormat("HH_mm_ss_dd_MM_yyyy");
File snippetFile = new File(picDir, fileName+"_"+dateFormat.format(new Date())+".png");
try {
FileOutputStream fileOutputStream = new FileOutputStream(snippetFile);
BitmapManager.sBitmapSnippet.setHasAlpha(true);
BitmapManager.sBitmapSnippet.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The picture is shown only in the path, and the rest of the bounding box is black and not transparent.
I appreciate any help.
I'm using compress() method to write bitmap into output stream:
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
It is important to use PNG format. JPEG transforms my transparent background into black color.
I don't know why exactly does it lose transparency, but I had the same problem. All you have to do is to change
BitmapManager.sBitmapSnippet.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
to
BitmapManager.sBitmapSnippet.compress(Bitmap.CompressFormat.PNG, 0, fileOutputStream);.
This will compress the bitmap with full quality, but containing transparent regions.
Don't loose transparency by this small snippet
Here Problem is you save image in .JPEG so JPEG take black background as transparent so we will save in .PNG so definitely get transparent Image
private void saveImage(Bitmap data, View view) {
File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Magic PhotoShoot");
if (!createFolder.exists())
createFolder.mkdir();
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());
File saveImage = new File(createFolder, "Photoshoot_" + strDate + ".png");
try {
OutputStream outputStream = new FileOutputStream(saveImage);
data.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
Snackbar.make(view, "Saved to PhotoShoot successfully", Snackbar.LENGTH_SHORT).show();
isSave = true;
Glob.savedImage = saveImage.getAbsolutePath();
MediaStore.Images.Media.insertImage(getContentResolver(), saveImage.getAbsolutePath(), saveImage.getName(), saveImage.getName());
} catch (FileNotFoundException e) {
Snackbar.make(view, "File not found", Snackbar.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
Snackbar.make(view, "Error while saving image", Snackbar.LENGTH_SHORT).show();
e.printStackTrace();
}
}
JPEG does not support transparency. JPEG's lossy compression also suffers from generation loss, where repeatedly decoding and re-encoding an image to save it
Use PNG extension file format for storing images in storage
In Kotlin:
Here is bitmap which is used for compression and saving into storage using file path
val file=File(outputImagePath)
var fout: OutputStream? = null
fout = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout)
fout.flush()
fout.close()`
In Java:
Here is bitmap which is used for compression and saving into storage using file path
File imageFile = new File(outputImagePath);
OutputStream fout = null;
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
fout.flush();
fout.close();
You should use Bitmap.CompressFormat.PNG or Bitmap.CompressFormat.WEBP. If you want to get less size image. you should use Bitmap.CompressFormat.WEBP like me.

Drawing text on bitmap in android

I am drawing a text on bitmap in android application and then i am saving it in sd-card.
the image getting saved but there is no text, i mean it seems that there some problem in drawtext, this is my code
Bitmap bitmap = Bitmap.createBitmap(370, 177, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
c.drawColor(0xffffffff);
Paint p = new Paint();
p.setColor(R.color.black);
//p.setStyle(Style.FILL);
//p.setStrokeWidth(40.0f);
//p.setTextSize(40.0f);
//p.setTextAlign(Align.RIGHT);
c.drawText("Some text", 70, 77, p);
//c.save();
try {
FileOutputStream fos = new FileOutputStream(myfile);
bitmap.compress(CompressFormat.PNG, 90, fos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bitmap.recycle();
am i forget something or what's wrong with this code ?
R.color.black is not a real color but just a reference to a color value.
Replace it with Color.BLACK or getResources().getColor(R.color.black)
p.setColor(Color.BLACK);
OR
p.setColor(getResources().getColor(R.color.black));

How can I save canvas of ImageView to a Bitmap?

I've got an ImageView, in its onDraw(canvas),
i tried:
canvas.drawBitmap(...);//draw an extremely large background 3264 * 2448 pixels
canvas.drawLine(...);//draw target
My question is, how can I save this canvas into a sth like png? Thanks!
From the question here:
Drawing on Canvas and save image
imgView.setDrawingCacheEnabled(true);
Bitmap b = imgView.getDrawingCache();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(getFileName());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
b.compress(CompressFormat.PNG, 95, fos);
You can save the view cache image to the disk as png.

android: convert canvas to bitmap then save to SD card

i'm developing an android app where I can draw on a canvas. I want to convert my canvas to bitmap and then save it in jpeg format on my sd card..
how can i properly do this?
Something like that should work :
http://developer.android.com/reference/android/view/View.html#getDrawingCache(boolean)
public void toJPEGFile(){
File folder = new File(Environment.getExternalStorageDirectory()+"/folder/");
if(!folder.exists()) folder.mkdirs();
try {
this.setDrawingCacheEnabled(true);
FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/folder/file"));
Bitmap bitmap = this.getDrawingCache();
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Did you look up the documentation?
Canvas API
You can use the:
public Canvas (Bitmap bitmap)
Since: API Level 1
Construct a canvas with the specified bitmap to draw into. The bitmap must be mutable.
The initial target density of the canvas is the same as the given bitmap's density.
Parameters
bitmap Specifies a mutable bitmap for the canvas to draw into.

Categories

Resources