Bitmap size exceed VM budget - android

I have read those posts on this issue but my case is abit different as I am NOT DISPLAYING the bitmap but just post-processing the image from raw data.
First, I call ImageProcessing.rgbToBitmap(data,width, height); which will return a Bitmap object. Then I perform these 3 functions SEPARATELY.
Rotate Bitmap
Add a watermark overlay to Bitmap
Add date at lower right hand corner of Bitmap
All 3 methods called will create an return a Bitmap object which probably causes the crash as I am trying to save an image every 1000ms! Sometimes the images saved are distorted probably due to the memory error.
I am posting my codes below and any advices are greatly appreciated. I do not want to compromise on the quality on the image taken though. (Need to preserve the resolution)
public static Bitmap addWatermark(Resources res, Bitmap source) {
int w, h;
Canvas c;
Paint paint;
Bitmap bmp, watermark;
Matrix matrix;
float scale;
RectF r;
w = source.getWidth();
h = source.getHeight();
// Create the new bitmap
bmp = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG
| Paint.FILTER_BITMAP_FLAG);
// Copy the original bitmap into the new one
c = new Canvas(bmp);
c.drawBitmap(source, 0, 0, paint);
// Load the watermark
watermark = BitmapFactory.decodeResource(res, R.drawable.watermark);
// Scale the watermark to be approximately 10% of the source image
// height
scale = (float) (((float) h * 0.80) / (float) watermark.getHeight());
// Create the matrix
matrix = new Matrix();
matrix.postScale(scale, scale);
// Determine the post-scaled size of the watermark
r = new RectF(0, 0, watermark.getWidth(), watermark.getHeight());
matrix.mapRect(r);
// Center watermark
matrix.postTranslate((w - r.width()) / 2, (h - r.height()) / 2);
// Draw the watermark
c.drawBitmap(watermark, matrix, paint);
// Free up the bitmap memory
watermark.recycle();
return bmp;
}
public static Bitmap addDate(Bitmap src, String date) {
int w = src.getWidth();
int h = src.getHeight();
//Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
Bitmap result = src;
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Paint paint = new Paint();
paint.setColor(Color.rgb(255, 185, 15));
paint.setTextSize(20);
paint.setAntiAlias(true);
canvas.drawText(date, w - 200, h - 20, paint);
return result;
}
public static Bitmap rotate(Bitmap src, int rotation) {
int width = src.getWidth();
int height = src.getHeight();
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// rotate the Bitmap
matrix.postRotate(rotation);
// recreate the new Bitmap, swap width and height and apply
// transform
Bitmap rotatedBitmap = Bitmap.createBitmap(src, 0, 0, width, height,
matrix, true);
return rotatedBitmap;
}

Try this first:
Change
// Copy the original bitmap into the new one
c = new Canvas(bmp);
c.drawBitmap(source, 0, 0, paint);
with
// Copy the original bitmap into the new one
c = new Canvas(bmp);
bmp.recycle(); //here or below
c.drawBitmap(source, 0, 0, paint);
//below bmp.recycle();
and here:
canvas.drawText(date, w - 200, h - 20, paint);
return result;
with
canvas.drawText(date, w - 200, h - 20, paint);
result.recycle();
return result;
and here
Bitmap rotatedBitmap = Bitmap.createBitmap(src, 0, 0, width, height,
matrix, true);
return rotatedBitmap;
with
Bitmap rotatedBitmap = Bitmap.createBitmap(src, 0, 0, width, height,
matrix, true);
return rotatedBitmap;
rotatedBitmap.recycle();
Add all this (recycle();) maybe this is already enough and also try the code with smaller bitmaps, en see if it still crashes (like 50px by 50px).
And no, their is no way to increase the VM of your phone.

Related

How to make any bitmap in cylinder shape just like image added to any mug in Android

`
There is an requirement in my project to set any bitmap into mug and also edit bitmap and wright some text on image then past this bitmap to mug just like attached image .
I need a solution in Android or any supported library, Before I have tried to do this with Android Canvas and its method to draw arc But not reached my requirement.
/**
* Draw one image over other using the canvas paint and path drawing.
*/
public Bitmap createMaskedImageInImageCenterRightMug(Drawable back,
Bitmap bitmapToDrawInTheCenter) {
Bitmap backgroundBitmap = ((BitmapDrawable) back).getBitmap();
int hieghtBack = backgroundBitmap.getHeight();
int widthBack = backgroundBitmap.getWidth();
int hieghtFront = bitmapToDrawInTheCenter.getHeight();
int widthFront = bitmapToDrawInTheCenter.getWidth();
int widthToDrawOnMug = widthBack / 2;
backgroundBitmap = Bitmap.createScaledBitmap(backgroundBitmap, (int) canvas_width, hieghtBack, true);
// Create mask
Bitmap backgroundBitmapMask = Bitmap.createBitmap(backgroundBitmap, 7, 0, (int) (canvas_width / 2), hieghtBack);
if (widthToDrawOnMug <= widthFront) {
bitmapToDrawInTheCenter = Bitmap.createBitmap(
bitmapToDrawInTheCenter, (widthFront * 40) / 100, 0,
(widthFront * 60) / 100, hieghtFront);
}
Bitmap backgroundBitmapScaledMask = Bitmap.createScaledBitmap(
backgroundBitmapMask, widthToDrawOnMug, hieghtBack - 50, true);
bitmapToDrawInTheCenter = Bitmap.createScaledBitmap(
bitmapToDrawInTheCenter, backgroundBitmapScaledMask.getWidth(),
backgroundBitmapScaledMask.getHeight(), true);
Bitmap resultBitmap = Bitmap.createBitmap(
backgroundBitmapScaledMask.getWidth(),
backgroundBitmapScaledMask.getHeight(),
backgroundBitmapScaledMask.getConfig());
Canvas canvas = new Canvas(resultBitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(backgroundBitmapScaledMask, 0, 0, null);
canvas.drawBitmap(bitmapToDrawInTheCenter, 0, 0, paint);
return resultBitmap;
}
/**
* Draw one image over other using the canvas paint and path drawing.
*/
public Bitmap pasteOverMugForRightMug(Drawable back,
Bitmap bitmapToDrawInTheCenter) {
Bitmap backgroundBitmap = ((BitmapDrawable) back).getBitmap();
Bitmap resultBitmap = Bitmap.createBitmap(backgroundBitmap.getWidth(), backgroundBitmap.getHeight(), backgroundBitmap.getConfig());
Canvas canvas = new Canvas(resultBitmap);
canvas.drawBitmap(backgroundBitmap, new Matrix(), null);
Paint paint = new Paint();
canvas.drawBitmap(bitmapToDrawInTheCenter, 0, 25, paint);
return resultBitmap;
}
Here is my code . Some hard code values are used according plain Mug image Aspect Ratio.
Also Tried to do this with Open GL but it was very complex .
And and could not find method for cylinder shape in one of the image processing library Image magic.
if any one have an idea please share .

Crop picture from camera by code not by user (Create Bitmap)

I'm trying to crop a picture from camera but it is shown zoomed. the width and height are ok but it's zoomed a lot.
This is my code :
This is the code I use for scaling bitmaps, the wantedWidth and wantedHeight would be the width and height of your view.
public static Bitmap scaleBitmap(Bitmap bitmap, int wantedWidth, int wantedHeight) {
Bitmap output = Bitmap.createBitmap(wantedWidth, wantedHeight, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Matrix m = new Matrix();
m.setScale((float) wantedWidth / bitmap.getWidth(), (float) wantedHeight / bitmap.getHeight());
canvas.drawBitmap(bitmap, m, new Paint());
return output;
}

How to crop image in oval shape or facemask shape in android?

I am doing camera application.i have capture and crop image in square shape. But i need oval shape or human face shape. How is it come ?
I have used following method and passed my captured bitmap image to this method. And it will work.
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 125;
int targetHeight = 125;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(
((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(
sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap
.getHeight()), new Rect(0, 0, targetWidth,
targetHeight), p);
return targetBitmap;
}
And the output is as follows:-
I used following in one of my project. May be this helps you.
public Drawable getRoundedCornerImage(Drawable bitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable)bitmapDrawable).getBitmap();
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 10;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
Drawable image = new BitmapDrawable(output);
return image;
}
Explore com.android.camera.CropImage.java sources. It can crop circle images.
// if we're circle cropping we'll want alpha which is the third param here
464 mCroppedImage = Bitmap.createBitmap(width, height,
465 mCircleCrop ?
466 Bitmap.Config.ARGB_8888 :
467 Bitmap.Config.RGB_565);
468 Canvas c1 = new Canvas(mCroppedImage);
469 c1.drawBitmap(mBitmap, r, new Rect(0, 0, width, height), null);
470
471 if (mCircleCrop) {
472 // OK, so what's all this about?
473 // Bitmaps are inherently rectangular but we want to return something
474 // that's basically a circle. So we fill in the area around the circle
475 // with alpha. Note the all important PortDuff.Mode.CLEAR.
476 Canvas c = new Canvas (mCroppedImage);
477 android.graphics.Path p = new android.graphics.Path();
478 p.addCircle(width/2F, height/2F, width/2F, android.graphics.Path.Direction.CW);
479 c.clipPath(p, Region.Op.DIFFERENCE);
480
481 fillCanvas(width, height, c);
482 }
#vokilam you are right; I just explored into code and found a way to work around...
Just include this line in the main Activity
intent.putExtra(CropImage.CIRCLE_CROP, "circleCrop");
But you will only get circles, not oval; so #amarnathreddy you cannot cut perfect human face with this; instead go for Grabcut of OpenCv
Try with this ...to crop in human face shape
Uri ImageCaptureUri = Uri.fromFile(new File("filepath");
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
intent.setData(ImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
For an oval shape try this android function or download demo here
public static Bitmap getOvalCroppedBitmap(Bitmap bitmap, int radius) {
Bitmap finalBitmap;
if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
false);
else
finalBitmap = bitmap;
Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Paint paint = new Paint();
final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
finalBitmap.getHeight());
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
RectF oval = new RectF(0, 0, 130, 150);
canvas.drawOval(oval, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(finalBitmap, rect, oval, paint);
return output;
}
The above function creates a uniform oval shape in android programmatically.
call your function onCreate function and pass the image to crop oval shape as a bitmap image
Read more

android slicing image into 10 equal pieces

I have got images which I want to slice into 10 pieces vertically of equal height so on hdpi slice dimensions are 800*48 (landscape application). I have got following code which is not working
public void convertBitmapinSlices(){
Bitmap tempBitmap;
try{
Paint paint = new Paint();
paint.setFilterBitmap(true);
tempBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
int targetWidth = (int) Methods.dpToPx(tempBitmap.getWidth(), this);
Log.v("TARGET_WIDTH", Integer.toString(targetWidth));
int targetHeight = (int) (Methods.dpToPx(tempBitmap.getHeight(), this)/10);
Log.v("TARGET_HEIGHT", Integer.toString(targetHeight));
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,Bitmap.Config.ARGB_8888);
RectF rectf = new RectF(0, 0, targetWidth, targetHeight);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addRect(rectf, Path.Direction.CW);
canvas.clipPath(path);
int starty=0;
lLforGardenImages.removeAllViews();
for(int i=1; i<=10;i++){
Log.v("SRC-Height", Integer.toString(targetHeight*i));
Log.v("START-Y", Integer.toString(starty));
canvas.drawBitmap(tempBitmap, new Rect(0, starty, tempBitmap.getWidth(), (tempBitmap.getHeight()/10)+starty),
new Rect(0, 0, targetWidth,targetHeight), paint);
// Matrix matrix = new Matrix();
// matrix.postScale(1f, 1f);
Bitmap resizedBitmap = Bitmap.createBitmap(targetBitmap, 0, 0, targetWidth, targetHeight, null, true);
Log.v("Width after Resizing ", resizedBitmap.getWidth()+"");
Log.v("Height after Resizing ", resizedBitmap.getHeight()+"");
BitmapDrawable bd = new BitmapDrawable(resizedBitmap);
ImageView iv = new ImageView(this);
iv.setAdjustViewBounds(true);
iv.setBackgroundDrawable(bd);
lLforGardenImages.addView(iv, llayoutParams);
if((i % 2) == 0){
iv.startAnimation(sliderAnimation(-1.0f,0.0f,0.0f,0.0f,1000));
}else{
iv.startAnimation(sliderAnimation(1.0f,0.0f,0.0f,0.0f,1000));
}
starty= starty+targetHeight;
}
}
catch(Exception e){
System.out.println("Error1 : " + e.getMessage() + e.toString());
}
}
Any idea what I am doing wrong?
Output is that slice is not correct and have contents which seems to have smaller height but height of slice is correct i.e 48 and width is correct too. So only issue with above code is that contents height seems to be incorrect even though slice height is correct.

How might I add a watermark effect to an image in Android?

I have an image with frames and I need to add a watermark effect. How might I do this?
I found great tutorial on Android Image Processing here.
public static Bitmap mark(Bitmap src, String watermark, Point location, Color color, int alpha, int size, boolean underline) {
int w = src.getWidth();
int h = src.getHeight();
Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Paint paint = new Paint();
paint.setColor(color);
paint.setAlpha(alpha);
paint.setTextSize(size);
paint.setAntiAlias(true);
paint.setUnderlineText(underline);
canvas.drawText(watermark, location.x, location.y, paint);
return result;
}
Thanks to Pete Houston who shares such useful tutorial on basic image processing.
For others reference, if you want to add the logo of your application (which is in your drawable folder(s)) on top of image use following method:
private Bitmap addWaterMark(Bitmap src) {
int w = src.getWidth();
int h = src.getHeight();
Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Bitmap waterMark = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.logo);
canvas.drawBitmap(waterMark, 0, 0, null);
return result;
}
If someone is still searching for this, I found a good solution here
It adds a watermark to the bottom right portion and scales it according to the source image which was exactly what I was looking for.
/**
* Embeds an image watermark over a source image to produce
* a watermarked one.
* #param source The source image where watermark should be placed
* #param watermark Watermark image to place
* #param ratio A float value < 1 to give the ratio of watermark's height to image's height,
* try changing this from 0.20 to 0.60 to obtain right results
*/
public static Bitmap addWatermark(Bitmap source, Bitmap watermark, float ratio) {
Canvas canvas;
Paint paint;
Bitmap bmp;
Matrix matrix;
RectF r;
int width, height;
float scale;
width = source.getWidth();
height = source.getHeight();
// Create the new bitmap
bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG);
// Copy the original bitmap into the new one
canvas = new Canvas(bmp);
canvas.drawBitmap(source, 0, 0, paint);
// Scale the watermark to be approximately to the ratio given of the source image height
scale = (float) (((float) height * ratio) / (float) watermark.getHeight());
// Create the matrix
matrix = new Matrix();
matrix.postScale(scale, scale);
// Determine the post-scaled size of the watermark
r = new RectF(0, 0, watermark.getWidth(), watermark.getHeight());
matrix.mapRect(r);
// Move the watermark to the bottom right corner
matrix.postTranslate(width - r.width(), height - r.height());
// Draw the watermark
canvas.drawBitmap(watermark, matrix, paint);
return bmp;
}
And it is well commented which is what is a huge plus!
It seems you are looking for a waterrippleeffect as this one. Checkout the complete source code. Also check the screenshot how does the effect look like.
In Kotlin:
Note: Its just modified code of above answers
private fun mark(src: Bitmap, watermark: String): Bitmap {
val w = src.width
val h = src.height
val result = Bitmap.createBitmap(w, h, src.config)
val canvas = Canvas(result)
canvas.drawBitmap(src, 0f, 0f, null)
val paint = Paint()
paint.color = Color.RED
paint.textSize = 10f
paint.isAntiAlias = true
paint.isUnderlineText = true
canvas.drawText(watermark, 20f, 25f, paint)
return result
}
val imageBitmap = mark(yourBitmap, "Your Text")
binding.meetProofImageView.setImageBitmap(imageBitmap)
You can use androidWM to add a watermark into your image, even with invisible watermarks:
add dependence:
dependencies {
...
implementation 'com.huangyz0918:androidwm:0.2.3'
...
}
and java code:
WatermarkText watermarkText = new WatermarkText(“Hello World”)
.setPositionX(0.5)
.setPositionY(0.5)
.setTextAlpha(100)
.setTextColor(Color.WHITE)
.setTextFont(R.font.champagne)
.setTextShadow(0.1f, 5, 5, Color.BLUE);
WatermarkBuilder.create(this, backgroundBitmap)
.loadWatermarkText(watermarkText)
.getWatermark()
.setToImageView(backgroundView);
You can easily add an image type watermark or a text watermark like this, and the library size is smaller than 30Kb.
I tried a few libraries mentioned in other posts, like this, but unfortunately it is missing, and not downloadable now. So I followed AndroidLearner 's answer above, but after tweaking the code a little bit, for those of you who are having trouble rotating the watermark, and what values are valid for the various methods of Paint class, so that the text shows rotated at an angle(like most of the company watermarks do), you can use the below code.
Note that, w and h are the screen width and height respectively, which you can calculate easily, there are tons of ways you can find on stackoverflow only.
public static Bitmap waterMarkBitmap(Bitmap src, String watermark) {
int w = src.getWidth();
int h = src.getHeight();
Bitmap mutableBitmap = Utils.getMutableBitmap(src);
Bitmap result = Bitmap.createBitmap(w, h, mutableBitmap.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0f, 0f, null);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(92f);
paint.setAntiAlias(true);
paint.setAlpha(70); // accepts value between 0 to 255, 0 means 100% transparent, 255 means 100% opaque.
paint.setUnderlineText(false);
canvas.rotate(45, w / 10f, h / 4f);
canvas.drawText(watermark, w / 10f, h / 4f, paint);
canvas.rotate(-45, w / 10f, h / 4f);
return result;
}
It rotates the text watermark by 45 degrees, and places it at the centre of the bitmap.
Also note that, in case you are not able to get watermark, it might be the case that the bitmap you are using as source is immutable. For this worst case scenario, you can use below method to create a mutable bitmap from an immutable one.
public static Bitmap getMutableBitmap(Bitmap immutableBitmap) {
if (immutableBitmap.isMutable()) {
return immutableBitmap;
}
Bitmap workingBitmap = Bitmap.createBitmap(immutableBitmap);
return workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
}
I found above method inside here. I have tested using both the methods in my application, and it works perfectly after I added above tweaks. Try it and let me know if it works or not.
use framelayout. put two imageviews inside the framelayout and specify the position of the watermark imageview.

Categories

Resources