Android Paint PorterDuff.Mode.CLEAR - android

I'm working on application which is drawing on Canvas similar to Finger Paint demo from Android SDK. My problem is when I'm using PorterDuff.Mode.CLEAR. When drawing and Canvas and if I try to erase something, it's working fine. But if I try to save my image as PNG file the strokes of eraser are coloured black, and I'm not sure why is this happening. Here is an example what I'm doing :
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
Eraser :
case ERASE_MENU_ID:
mPaint.setXfermode(new PorterDuffXfermode(
PorterDuff.Mode.CLEAR));
return true;
And how I'm saving the image :
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("yyyyMMMddHmmss");
String dateNow = formatter.format(currentDate.getTime());
File dir = new File(mImagePath);
if(!dir.exists())
dir.mkdirs();
File file = new File(mImagePath + "/" + dateNow +".png");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
Toast.makeText(getApplicationContext(), "File saved at \n"+mImagePath + "/" + dateNow +".png", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Log.e("Panel", "FileNotFoundException", e);
}
catch (IOException e) {
Log.e("Panel", "IOEception", e);
}
return true;
And here is an example of images :
here is what my canvas looks like before saving :
and here is the image after saving it on sd card :

The problem with the fingerpaint code is that what you see is not the same that is compressed into the png. Look at onDraw(). First you draw the screen white. Then you add the Bitmap. Because you used Porter Duff Clear the erased part of the bitmap contains actually transparent black pixels (value 0x00000000). But because you have the white background these black pixels show as white.
To fix this either change your save code to do the same thing as the draw code
try {
fos = new FileOutputStream(file);
Bitmap saveBitmap = Bitmap.createBitmap(mBitmap);
Canvas c = new Canvas(saveBitmap);
c.drawColor(0xFFFFFFFF);
c.drawBitmap(mBitmap,0,0,null);
saveBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
saveBitmap.recycle();
...
or don't use PortDuff.Clear:
case ERASE_MENU_ID:
mPaint.setColor(Color.WHITE);

Related

Android studio (Chipmunk) screen capture image gets darken

I am programming a simple drawing application with drawLines:
public void onDraw(Canvas canvas) {
setBackgroundColor(cfgBackground); //background
//canvas.drawColor(ConfigActivity.getCfgBackground(ConfigActivity.cfgBackground)); //to keep background when export to PNG/JPG
//title
paint.setColor(0xbb020a0d);
paint.setTextSize(40);
canvas.drawText(Title, 0, 40, paint);
paint.setColor(color);
paint.setStrokeWidth(thickness);
canvas.drawLines(lines, paint);
}
This is no problem. When export the screen to image file, the image shows normal in the preview screen (with all other photos in the phone), but when open this image, it shows darken, as following:
I have tried Method A/B/C like following, but the result not much different:
File sdCard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(sdCard, imageName);
FileOutputStream fos = null;
try {
// Make sure the Pictures directory exists.
sdCard.mkdirs();
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
Toast.makeText(getContext(), file + " open failed: " + e, Toast.LENGTH_SHORT).show();
e.printStackTrace();
return;
}
/* //method A: will get dark image
setDrawingCacheEnabled(true);
Bitmap b = getDrawingCache();
//b.setHasAlpha(true); //to set transparency
//Canvas canvas = new Canvas(b);
//canvas.drawColor(cfgBackground)); //trying to solve darken image
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
setDrawingCacheEnabled(false); //for next screen update
*/
Bitmap b = screenShot(this); //Method B
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
try {
fos.flush();
fos.close();
} catch (IOException e) {
Toast.makeText(getContext(), file + " save failed: " + e, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
Toast.makeText(getContext(), file + " saved in Albums", Toast.LENGTH_SHORT).show();
//add to gallary
getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.toString())));
Two functions:
//Method C
public static Bitmap getBitmapFromView(View view) {
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null)
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
else
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(cfgBackground);
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
//Method B
public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Anyone encountered this problem?
I finally found the solution (although not sure why): the background color should be 0xFFrrggbb, eg. 0xffeeee00, though the background looks ugly but just needs more finetune...
If you know why, kindly share here, appreciated!

Attaching text to screenshot taken programatically

I need to save the content of a webview as image for making it easier for sharing.
I managed to save the content of the webview as image (though I have to goto landscape mode for making the image smaller in height - I can't get it within the portrait!) but I need to attach some text and a watermark image to the bottom of the saved screenshot of webview.
Can any one help me to do so?
My code
if (webContentHeight <= 0) webContentHeight = wbContent.getContentHeight();
Bitmap bitmap = Bitmap.createBitmap(wbContent.getWidth(), (int) (webContentHeight * 1.5), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
wbContent.layout(0, 0, wbContent.getLayoutParams().width, wbContent.getLayoutParams().height);
wbContent.draw(canvas);
File imgDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "imgDir");
if (!imgDir.exists()) imgDir.mkdirs();
File imagePath = new File(imgDir, "Item_" +
new SimpleDateFormat("ddMMyyyy_hhmmss").format(new Date()) + ".png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
startActivity(new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.parse("file://" + imagePath.getAbsolutePath()), "image/*"));
if (Utils.IsNetworkConnected(getApplicationContext()))
new AsyncTsk_GrabContent().execute();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(context, "Can't save news as image. " + e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Can't save news as image. " + e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(context, "Can't save news as image. " + e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
if (Orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER);
if (pgDialog != null) {
pgDialog.dismiss();
pgDialog = null;
}
}
I tired this but can't meet the requirement :
canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(16);
canvas.drawText("My Text", 10, 10, paint);
wbContent.draw(canvas);
Thanks in Advance.
If you are drawing your text at (10,10), then drawing your wbContent at (0,0), you are drawing over your text. Either move the text down past 2/3 of the height of the canvas (as you seem to be intentionally making your canvas 1.5x the height of wbContent), or simply draw the text after drawing the wbContent.

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.

open and save same image again on android

I am trying to open a saved image in the gallery, and after writing some text on this opened image, trying to close it. But so far, it doesn't work. Could you tell me what I am doing wrong please?
**I checked the path, it is correct. Here is the my code :
String path = android.os.Environment.getExternalStorageDirectory().toString() + "/DCIM/100LGDSC/";
String pathiki = path+filename;
Log.d("pathiki:",pathiki);
try {
Bitmap bm = BitmapFactory.decodeFile(pathiki);
Typeface tf = Typeface.create("Helvetica", Typeface.BOLD);
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.WHITE);
paint.setTypeface(tf);
paint.setTextAlign(Align.CENTER);
paint.setTextSize(14);
Canvas canvas = new Canvas(bm);
canvas.drawText("bla bla bla", 100, 100, paint);
OutputStream fOut = new FileOutputStream(new File(pathiki));
bm.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
// TODO: handle exception
e.toString();
}
BitmapFactory.decodeFile always returns an immutable bitmap. Use Bitmap.copy to make a copy of bitmap which is mutable. Now perform modifications on the copied bitmap.
Bitmap bm = BitmapFactory.decodeFile(pathiki).copy(Bitmap.Config.ARGB_8888, true);
Update the exception handler code. Either log e.getMessage() to logcat or use e.printStackTrace().

not able to extract the drawing cache with overlayed bitmap images

I am trying to save a canvas on an sdcard. Basically I am drawing two bitmaps (one on top of another) in the onDraw(Canvas canvas) method. But when I save the file, only the bottom layered Bitmap is stored. I am posting the code for the onDraw method here:
Paint paint = new Paint();
paint.setColor(Color.BLACK);
//rectangle for the first image
rct = new Rect(10, 10, canvas.getWidth(), canvas.getHeight());
// rectangle for the second image, the secong image is drawn where the user touches the screen
new_image = new RectF(touchX, touchY, touchX + secondBitmap.getWidth(),
touchY + secondBitmap.getHeight());
//this is the bitmap that is drawn first
canvas.drawBitmap(firstBitmap, null, rct, paint);
//this is the bitmap drawn on top of the first bitmap on user touch
canvas.drawBitmap(secondBitmap, null, new_image, paint);
canvas.save();
the code for saving the canvas on the SDcard written on the MainActivity is:
Bitmap bm = canvas.getDrawingCache() // canvas in an object of the class I extended from View
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath();
boolean exists = (new File(path)).exists();
OutputStream outStream = null;
File file = new File(path, "drawn_image" + ".jpg");
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
The problem is that only the base image(firstBitmap of the onDraw() method) is saved on the SDCard instead of the entire canvas(with both the images). I am new to canvas...So any help would be very appreciated
when getDrawingcache() is called it invalidates the view to get the full cache. so debug your code and check if it is going through each and every line of your onDraw() method in view.

Categories

Resources