How to crop Bitmap Center like imageview? [duplicate] - android

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to crop the parsed image in android?
How does one crop the same way as Androids ImageView is doing
android:scaleType="centerCrop"

Your question is a bit short of information on what you want to accomplish, but I guess you have a Bitmap and want to scale that to a new size and that the scaling should be done as "centerCrop" works for ImageViews.
From Docs
Scale the image uniformly (maintain the image's aspect ratio) so that
both dimensions (width and height) of the image will be equal to or
larger than the corresponding dimension of the view (minus padding).
As far as I know, there is no one-liner to do this (please correct me, if I'm wrong), but you could write your own method to do it. The following method calculates how to scale the original bitmap to the new size and draw it centered in the resulting Bitmap.
Hope it helps!
public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
int sourceWidth = source.getWidth();
int sourceHeight = source.getHeight();
// Compute the scaling factors to fit the new height and width, respectively.
// To cover the final image, the final scaling will be the bigger
// of these two.
float xScale = (float) newWidth / sourceWidth;
float yScale = (float) newHeight / sourceHeight;
float scale = Math.max(xScale, yScale);
// Now get the size of the source bitmap when scaled
float scaledWidth = scale * sourceWidth;
float scaledHeight = scale * sourceHeight;
// Let's find out the upper left coordinates if the scaled bitmap
// should be centered in the new size give by the parameters
float left = (newWidth - scaledWidth) / 2;
float top = (newHeight - scaledHeight) / 2;
// The target rectangle for the new, scaled version of the source bitmap will now
// be
RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
// Finally, we create a new bitmap of the specified size and draw our new,
// scaled bitmap onto it.
Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(source, null, targetRect, null);
return dest;
}

Related

Making Bitmap aspect ratio to centerFit Android

I have searched alot for this but got no proper solution!
i have a drawing area in my android app and i want to take image from camera/gallery and set it as a background of canvas.
I get Bitmap after taking photo from camera/gallery and i pass my bitmap to this method to make it aspect fit to my drawView keeping its aspect ratio.
Here newHeight/newWidth are my drawView's height and width.
public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
int sourceWidth = source.getWidth();
int sourceHeight = source.getHeight();
// Compute the scaling factors to fit the new height and width, respectively.
// To cover the final image, the final scaling will be the bigger
// of these two.
float xScale = (float) newWidth / sourceWidth;
float yScale = (float) newHeight / sourceHeight;
float scale = Math.min(xScale, yScale);
// Now get the size of the source bitmap when scaled
float scaledWidth = scale * sourceWidth;
float scaledHeight = scale * sourceHeight;
// Let's find out the upper left coordinates if the scaled bitmap
// should be centered in the new size give by the parameters
float left = (newWidth - scaledWidth) / 2;
float top = (newHeight - scaledHeight) / 2;
// The target rectangle for the new, scaled version of the source bitmap will now
// be
RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
// Finally, we create a new bitmap of the specified size and draw our new,
// scaled bitmap onto it.
Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
Canvas canvas = new Canvas(dest);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(source, null, targetRect, null);
return dest;
}
It works good on mt Htc m7 but on my galaxy tab4 it makes image strech so sleek as you can see in image below:
do anyone know any method through which i can set bitmap to my drawView like this
Bitmap backgroundBitMap= c.scaleCenterCrop(bmp, drawView.getHeight(), drawView.getWidth());
String tempPath = getPath(selectedImageUri, MainActivity.this);
backgroundBitMap= c.rotateImage(backgroundBitMap,tempPath);
drawView.setBackgroundDrawable(new BitmapDrawable(backgroundBitMap));
but keeping its aspect ration same. Actually i want CenterFit functionality for a bitmap.
Any help would be appreciated! Thanks

Resizing an image to fit on a imageview

I am developing an application in which I need to fit an Bitmap into Imageview with specific dimensions(let's suppose 350dpx50dp - height*width).
I wanted to do something similar like this: http://gyazo.com/d739d03684e46411feb58d66acea1002
I have looked here for solutions. I found this code for scale the bitmap and fit it into imageview, but the problem is that imageview becomes greater when I add the bitmap into him:
private void scaleImage(Bitmap bitmap, ImageView view)
{
// Get current dimensions AND the desired bounding box
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int bounding = dpToPx(350);
// Determine how much to scale: the dimension requiring less scaling is
// closer to the its side. This way the image always stays inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) bounding) / width;
float yScale = ((float) bounding) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap and convert it to a format understood by the ImageView
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
// Apply the scaled bitmap
view.setImageBitmap(scaledBitmap);
}
Using this code I can get this : http://gyazo.com/e9871db2130ac33668156fc0cf773594
But that's not what I wanted, I want to keep the dimensions of imageview and add the bitmap into imageview without modifying the dimensions of imageview and occupying all the imageview's surface. Like the first image.
Why don't you just add android:scaleType="fitXY" to your ImageView in xml?

Scaling a bitmap to height and width of sceen

I have a bitmap image that is larger than then screen size. I want to scale the image in pixels down to the screen size ? How can i do this ? I want to scale it maintaining aspect ratio not just resize it ?
Kind Regards
Get the screen size and pass those parameters into the following function :
Bitmap.createScaledBitmap(originalimage, width, height, true);
use this function with argument as screenWidth and screenHeight
public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
int sourceWidth = source.getWidth();
int sourceHeight = source.getHeight();
// Compute the scaling factors to fit the new height and width, respectively.
// To cover the final image, the final scaling will be the bigger
// of these two.
float xScale = (float) newWidth / sourceWidth;
float yScale = (float) newHeight / sourceHeight;
float scale = Math.max(xScale, yScale);
// Now get the size of the source bitmap when scaled
float scaledWidth = scale * sourceWidth;
float scaledHeight = scale * sourceHeight;
// Let's find out the upper left coordinates if the scaled bitmap
// should be centered in the new size give by the parameters
float left = (newWidth - scaledWidth) / 2;
float top = (newHeight - scaledHeight) / 2;
// The target rectangle for the new, scaled version of the source bitmap will now
// be
RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
// Finally, we create a new bitmap of the specified size and draw our new,
// scaled bitmap onto it.
Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(source, null, targetRect, null);
return dest;
}
for how to get screen width and height see this

Android: How to get bitmap's scaled width in onDraw()

Simple question where the simple answer isn't working. I have a bitmap and I want to get its dimensions as scaled to the display by the system for different DPI screens within the onDraw() method. bitmap.width() returns its unscaled width successfully. However, bitmap.getScaledWidth() returns zero. I have tried getScaledWidth(canvas) and getScaledWidth(canvas.getDensity()), but both return 0. Indeed, canvas.getDensity() returns zero so I can't even calculate it manually.
What am I doing wrong?
Bit more detail. I'm using a custom view. The bitmap is declared in the class and loaded in the constructor.
Edit:
I've found that using:
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
bitmap.getScaledHeight(metrics) returns the same value as bitmap.getHeight().
It would appear that bitmap.getWidth() returns the dimension of the resident bitmap after it has been scaled, meaning there's no apparent way to get the bitmap's original width.
The Canvas class has a lots of overloads for the drawBitmap() function. One of them allows you to scale/cut a Bitmap through a pretty comfortable interface.
public void drawBitmap (Bitmap bitmap, Rect src, RectF dst, Paint paint)
Where
Bitmap bitmap - is your bitmap you want to draw
Rect src - the source rect from your bitmap. If its not null, it will
cut out a piece from your bitmap (in the size and position of src)
RectF dst - This Rect will represent the Rectangle, your Bitmap will
fit in.
Paint paint - optional paint
And now an example! Lets say, you want to shrink your Bitmaps width to 1/2 and increase its height to 2 times of the original:
float startX = 0; //the left
float startY = 0; //and top corner (place it wherever you want)
float endX = startX + bitmap.getWidth() * 0.5f; //right
float endY = startY + bitmap.getHeight() * 2.0f; //and bottom corner
canvas.drawBitmap(bitmap, null, new RectF(startX, startY, endX, endY), null);
UPDATE
I don't really understand, what you are trying to acomplish, after reading your comment, but here is some extra info to get started:
Get the original size of a Bitmap without loading it into the memory:
BitmapFactory.Options options = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = true; // bitmap wont be loaded into the memory
//won't load the Bitmap, but the options will contain the required information.
BitmapFactory.decodeStream(inputStream, null, options);
/*or*/ BitmapFactory.decodeFile(pathName, options);
int originalWidth = bitmapOptions.outWidth;
int originalHeight = bitmapOptions.outHeight;
Now if you have another your actual (scaled) Bitmap, or an ImageView, what you want to compare to the original, then you can use this (to get the width and height use getWidth() and getHeight()):
/*Get these values*/
int originalWidth, originalHeight, scaledWidth, scaledHeight;
float scaleWidthRatio = (float)scaledWidth / originalWidth;
float scaleHeightRatio = (float)scaledHeight / originalHeight;
How about this? You scale the bitmap yourself. :-)
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
Drawable drawable = getDrawable();
if(drawable==null)
Log.d("onDraw()","getDrawable returns null");
Bitmap fullSizeBitmap,scaledBitmap = null,roundBitmap = null;
fullSizeBitmap = ((BitmapDrawable)drawable).getBitmap() ;
//get width & height of ImageView
int scaledWidth = getMeasuredWidth();
int scaledHeight = getMeasuredHeight();
//bitmap, which will receive the reference to a bitmap scaled to the bounds of the ImageView.
if(fullSizeBitmap!=null)
scaledBitmap= getScaledBitmap(fullSizeBitmap,scaledWidth,scaledHeight);
//Now, draw the bitmap on the canvas
if(roundBitmap!=null)
canvas.drawBitmap(roundBitmap, 0,0 , null);
}

Android Image Resize basic

I like to resize an bitmap,if it is big make it small and place it on an specific location in the surface view, I need to get device width and height and then bitmap size and place them in an surface view and then take another image resize it and place it in any location has i like.
How to know the location co ordinates first(to place second image - this should be device independent if larger/smaller screen layout should not change)
and how to scale an big bitmap and set as background so i can draw an image over it.
my code :
final int canvasWidth = getWidth();
final int canvasHeight = getHeight();
int imageWidth = img.getWidth();
int imageHeight = img.getHeight();
float scaleFactor = Math.min( (float)canvasWidth / imageWidth,
(float)canvasHeight / imageHeight );
Bitmap scaled = Bitmap.createScaledBitmap( img,
(int)(scaleFactor * imageWidth),
(int)(scaleFactor * imageHeight),
true );
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(scaled, 10, 10, null);
this scale the big image but it doesn't fit the whole screen "img - bitmap is like an background image "
Someone can help me to understand the resize basics (I'm new so finding hard to understand resizing) to resize image to fit screen and resize any image to smaller one and place it in any location i like .
Store your bitmap as a source for manipulation and display it using ImageView:
Bitmap realImage = BitmapFactory.decodeFile(filePathFromActivity.toString());
Bitmap newBitmap = scaleDown(realImage, MAX_IMAGE_SIZE, true);
imageView.setImageBitmap(newBitmap);
//scale down method
public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
boolean filter) {
float ratio = Math.min(
(float) maxImageSize / realImage.getWidth(),
(float) maxImageSize / realImage.getHeight());
int width = Math.round((float) ratio * realImage.getWidth());
int height = Math.round((float) ratio * realImage.getHeight());
Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
height, filter);
return newBitmap;
}
And set your ImageView's width and height to "fill_parent".

Categories

Resources