This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to crop the parsed image in android?
I have an image in my res/drawable folder and I would like to crop (i.e. slice out some part of the image) the image when loading it into an ImageView. However I am unsure how to do this, any suggestions?
From Bitmap.createBitmap:
"Returns an immutable bitmap from the specified subset of the source bitmap. The new bitmap may be the same object as source, or a copy may have been made. It is initialized with the same density as the original bitmap."
Pass it a bitmap, and define the rectangle from which the new bitmap will be created.
// Take 10 pixels off the bottom of a Bitmap
Bitmap croppedBmp = Bitmap.createBitmap(originalBmp, 0, 0, originalBmp.getWidth(), originalBmp.getHeight()-10);
The Android Contact manager EditContactActivity uses Intent("com.android.camera.action.CROP")
This is a sample code:
Intent intent = new Intent("com.android.camera.action.CROP");
// this will open all images in the Galery
intent.setDataAndType(photoUri, "image/*");
intent.putExtra("crop", "true");
// this defines the aspect ration
intent.putExtra("aspectX", aspectY);
intent.putExtra("aspectY", aspectX);
// this defines the output bitmap size
intent.putExtra("outputX", sizeX);
intent.putExtra("outputY", xizeY);
// true to return a Bitmap, false to directly save the cropped iamge
intent.putExtra("return-data", false);
//save output image in uri
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
Try this:
ImageView ivPeakOver=(ImageView) findViewById(R.id.yourImageViewID);
Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.yourImageID);
int width=(int)(bmp.getWidth()*peakPercent/100);
int height=bmp.getHeight();
Bitmap resizedbitmap=Bitmap.createBitmap(bmp,0,0, width, height);
ivPeakOver.setImageBitmap(resizedbitmap);
From the Docs:
static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height)
Returns an immutable bitmap from the specified subset of the source bitmap.
If you want to equally crop the outside of the image, you should check out the ScaleType attribute for an ImageView: http://developer.android.com/reference/android/widget/ImageView.ScaleType.html
In particular, you would be interested in the "centerCrop" option. It crops out part of the image that is larger than the defined size.
Here's an example of doing this in the XML layout:
<ImageView android:id="#+id/title_logo"
android:src="#drawable/logo"
android:scaleType="centerCrop" android:padding="4dip"/>
int targetWidth = 100;
int targetHeight = 100;
RectF rectf = new RectF(0, 0, 100, 100);//was missing before update
Bitmap targetBitmap = Bitmap.createBitmap(
targetWidth, targetHeight,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addRect(rectf, Path.Direction.CW);
canvas.clipPath(path);
canvas.drawBitmap(
sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight),
null);
ImageView imageView = (ImageView)findViewById(R.id.my_image_view);
imageView.setImageBitmap(targetBitmap);
Related
I need to test a simple task. I want to create scaled bitmap by setting postScale to the Matrix and using it in the creation, here's a code:
Matrix matrix = new Matrix();
matrix.postScale(5.0f, 5.0f);
Bitmap bitmap = Bitmap.createBitmap(bitmapSrc, 500, 500, 50, 50, matrix, true);
I thought this code supposed to crop 50x50 bitmap from the source scaled in 5 times, but when i'm using this bitmap to show the result in ImageView
imageView.setImageBitmap(bitmap);
The scaling doesn't seem to work and i'm getting 50x50 bitmap from original source bitmap(without scaling).
I think i'm missing something, but i can't quite figure out what. Any help highly appreciated
Edit: I've also tried to set last parameter to false and it didn't help, but if i'm using postRotate in matrix i'm getting rotated bitmap
Android contains the function Bitmap.createScaledBitmap()...
You can use this as follows:
public Bitmap getScaledBitmap(Bitmap bitmap, float scale) {
Integer originalHeight = bitmap.getHeight();
Integer originalWidth = bitmap.getWidth();
Integer requiredHeight = Math.round(originalHeight * scale);
Integer requiredWidth = Math.round(originalWidth * scale);
return Bitmap.createScaledBitmap(bitmap, requiredWidth, requiredHeight, true);
}
You can checkout this for other relevant functions here.
It might be that the scaling happens too late and the crop area is out of bounds because of it. Did you try it with preScale instead of postScale?
If that does not work, you can try using coordinates within the small bitmap first, like this:
Bitmap bitmap = Bitmap.createBitmap(bitmapSrc, 100, 100, 10, 10, matrix, true);
I know how to crop a bitmap image from resources, but i want to cache image from ImageView to Bitmap, and then i want to crop it.
So, here is my code:
mImageViewArt.buildDrawingCache();
Bitmap bmap = mImageViewArt.getDrawingCache(); // works good
Bitmap bmp= BitmapFactory.decodeResource(getResources(),bmap); // Doesn't work(Cannot be aplied Int to Bitmap)
Bitmap resizedbitmap1 = Bitmap.createBitmap(bmp, 0, 0, 100, 100);
Why are you using the bmp intermediate variable?
If you want to crop the image returned by getDrawingCache(), you should just pass it as the input to Bitmap.createBitmap(), i.e.
mImageViewArt.buildDrawingCache();
Bitmap bmap = mImageViewArt.getDrawingCache();
Bitmap resizedbitmap1 = Bitmap.createBitmap(bmap, 0, 0, 100, 100);
I have checked many discussion but i can't seem to find an answer. How can i crop and large image taken by a camera and crop it to a 640x640 pixel size? Im returning a URI
EDIT: I would like to allow the user to crop the image!
Another solution would be to use the createScaledBitmap people use to create thumbnails.
byte[] imageData = null;
try
{
final int THUMBNAIL_SIZE = 64;
FileInputStream fis = new FileInputStream(fileName);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
}
catch(Exception ex) {
}
Your bitmap imageBitmap would probably have to come directly from your camera instead of a file, but the general idea stays the same.
You may use
private Bitmap crop(Bitmap src, int x, int y, int width, int height) {
Bitmap dst = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(dst);
canvas.drawBitmap(src, new Rect(0, 0, src.getWidth(), src.getHeight()),
new Rect(x, y, width, height), null);
return dst;
}
Type arguments are self explanatory.
Good luck.
Try this code, using the intent object:
intent.setType("image/*");
intent.putExtra("outputX", int_Height_crop);
intent.putExtra("outputY", int_Width_crop);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
use the below code
You can use this link also for your reference
Click Crop image using rectengle!
int targetWidth = 640;
int targetHeight = 640;
Bitmap targetBitmap = Bitmap.createBitmap(
targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addRect(rectf, Path.Direction.CW);
canvas.clipPath(path);
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), null);
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
imageView.setImageBitmap(targetBitmap);
I have been searching the net for this but couldn't find the any help.
I want to capture an Image by invoking camera and want to crop it. But the thing is instead of RECTANGULAR crop( given in image) tool I need a CIRCULAR one (second image).
Note: First image shows - crop rectangular area and then using some other function displays it in circular fashion.
while image two shows - crop image in circular shape.
All I found on net was to crop using this rectangular tool and then display the image in circular view. (But I want to crop in circular form)
What I am doing in onActivityResult function is-
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null)
{
Bitmap photo = extras.getParcelable("data");
//this method convert the rectangular cropped image to circular display.
GraphicsUtil gu= new GraphicsUtil();
Bitmap output = gu.getCircleBitmap(photo,16);
mImageView.setImageBitmap(output);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists()) f.delete();
break;
Code for GraphicsUtil function is as below -
public Bitmap getCircleBitmap(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xffff0000;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
paint.setDither(true);
paint.setFilterBitmap(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth((float) 4);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
So you can see. Image is cropped rectangular then passed to a function which display it in circular fashion.
I want that image is cropped in circular way by CROP_FROM_CAMERA intent only without using GraphicUtil function.
Since different manufacturers implement their own interfaces for camera, the first method below will not work in all cases. For example, it worked on my Nexus S running stock 2.3.6 and not on my Galaxy Nexus on stock 4.3. Anyway, if you want to be able to crop your image in a circular fashion from the default crop action call it in the following way:
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
intent.setData(imageUri); // Uri to the image you want to crop
intent.putExtra("outputX", Constants.PROFILE_PICTURE_SIZE);
intent.putExtra("outputY", Constants.PROFILE_PICTURE_SIZE);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("circleCrop", new String(""));
intent.putExtra("return-data", false);
File cropImageFile = new File(CROP_IMAGE_PATH); // Path to save the cropped image
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropImageFile));
startActivityForResult(intent, CROP); // CROP = Code to track the result in onActivityResult
This should start the default crop app that will look like this:
If you've read this post by commonsware, you know that this will not always work. I suggest including one of the libraries from his post. The first one from lvillani is the CropImage activity extracted AOSP. Include the library and make call it with an intent similar to the one above. Make sure you include the circleCrop param in the intent.
BitmapShader shader;
shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,
Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
RectF rect = new RectF(0.0f, 0.0f, width, height);
Bitmap circularBitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(circularBitmap);
canvas.drawArc(rect, 0, 360, true, paint);
now circularBitmap is holding the circular image.
I haven't tried this yet, but it should work...
I will assume you can get the image from the camera. Once you have that image, you can proceed as follows.
Get a Canvas to draw on a new bitmap. Create a Path object and call addCircle. Call clipPath on the Canvas passing your circular Path. Now draw the camera image to the Canvas and it should only draw inside the clipping area. Unlock the Canvas and use the new Bitmap to save out whatever type of image you want. Dispose of whatever resources as appropriate.
I would like to crop an image. But I got a problem:
How to define a default size for the crop. I would like when the rectangle appears for the crop to define the size and the position of it.
Regards
Wazol
use the below code
You can use this link also for your reference
Click Crop image using rectengle!
int targetWidth = 100;
int targetHeight = 100;
Bitmap targetBitmap = Bitmap.createBitmap(
targetWidth, targetHeight,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addRect(rectf, Path.Direction.CW);
canvas.clipPath(path);
canvas.drawBitmap( sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), null);
ImageView imageView = (ImageView)findViewById(R.id.my_image_view);
imageView.setImageBitmap(targetBitmap);
use Intent add Aspect Ratio adding outputX and outputY parameter
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 250);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
startActivityForResult(i, CROP_FROM_CAMERA);