crop large image taken from camera to 640x640pixel - android

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);

Related

How to convert YUV_420_888 image to bitmap [duplicate]

This question already has answers here:
Android Camera2 API YUV_420_888 to JPEG
(3 answers)
Closed 4 years ago.
I am working on AR project where i need to capture the current frame and save it to gallery. I am able to get the image using Frame class in AR core , but the format of image is YUV_420_888. I have already tried lots of solutions to covert this to bitmap but couldn't able to solve it.
This is how I convert to jpeg.
public Bitmap imageToBitmap(Image image, float rotationDegrees) {
assert (image.getFormat() == ImageFormat.NV21);
// NV21 is a plane of 8 bit Y values followed by interleaved Cb Cr
ByteBuffer ib = ByteBuffer.allocate(image.getHeight() * image.getWidth() * 2);
ByteBuffer y = image.getPlanes()[0].getBuffer();
ByteBuffer cr = image.getPlanes()[1].getBuffer();
ByteBuffer cb = image.getPlanes()[2].getBuffer();
ib.put(y);
ib.put(cb);
ib.put(cr);
YuvImage yuvImage = new YuvImage(ib.array(),
ImageFormat.NV21, image.getWidth(), image.getHeight(), null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0, 0,
image.getWidth(), image.getHeight()), 50, out);
byte[] imageBytes = out.toByteArray();
Bitmap bm = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
Bitmap bitmap = bm;
// On android the camera rotation and the screen rotation
// are off by 90 degrees, so if you are capturing an image
// in "portrait" orientation, you'll need to rotate the image.
if (rotationDegrees != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(rotationDegrees);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bm,
bm.getWidth(), bm.getHeight(), true);
bitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
}
return bitmap;
}

ImageView not using alphachannel of bitmap

I have a little problem with rendering an object offscreen to create a bitmap of it and displaying it in an imageview. It does not shot the alpha channel correctly.
It works fine, when I save the bitmap as png and loading it then. But when I directly load it into an imageview, I will see a white background, which is the actual background color without the alpha channel.
Here the code for exporting the bitmap from my EGL Surface:
public Bitmap exportBitmap() {
ByteBuffer buffer = ByteBuffer.allocateDirect(w*h*4);
GLES20.glReadPixels(0, 0, w, h, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer);
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
Log.i("Render","Terminating");
EGL14.eglMakeCurrent(oldDisplay, oldDrawSurface, oldReadSurface, oldCtx);
EGL14.eglDestroySurface(eglDisplay, eglSurface);
EGL14.eglDestroyContext(eglDisplay, eglCtx);
EGL14.eglTerminate(eglDisplay);
return bitmap;
}
And here the code for setting the imageview (r is the class containing the previous function):
Bitmap bm;
bm = r.exportBitmap();
ImageView infoView = (ImageView)findViewById(R.id.part_icon);
infoView.setImageBitmap(bm);
Do I have to set some flags on the ImageView or set something in the config of the bitmap?
I'll add some code examples plus images to clarify the problem:
First the way I want it to work:
bm = renderer.exportBitmap();
Second the way it works, with the save to png workaround:
bm = renderer.exportBitmap();
//PNG To Bitmap
String path = Environment.getExternalStorageDirectory()+"/"+getName()+".png";
bm.compress(CompressFormat.PNG, 100, new FileOutputStream(new File(path)));
bm = BitmapFactory.decodeFile(path);
Third to clarify my premultiplied. Alpha is taken into account the wrong way:
bm = renderer.exportBitmap();
for(int x=bm.getWidth()-50; x<bm.getWidth(); x++) {
for(int y=bm.getHeight()-50; y<bm.getHeight(); y++) {
int px = bm.getPixel(x,y);
bm.setPixel(x, y,
Color.argb(255,
Color.red(px),
Color.green(px),
Color.blue(px)));
}
}
Sorry for the long post.
I have changed the exportBitmap() function. Basically I read the pixels and write them again. This is solving the problem. I really don't know why. It would be nice, if somebody could explain it to me. It is not that clean to create a new integer array for these bitmapdata.
public Bitmap exportBitmap() {
ByteBuffer buffer = ByteBuffer.allocateDirect(w*h*4);
GLES20.glReadPixels(0, 0, w, h, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer);
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
//This is the modification
int[] pixels = new int[w*h];
bitmap.getPixels(pixels, 0, w,0, 0,w, h);
bitmap.setPixels(pixels, 0, w,0, 0,w, h);
EGL14.eglMakeCurrent(oldDisplay, oldDrawSurface, oldReadSurface, oldCtx);
EGL14.eglDestroySurface(eglDisplay, eglSurface);
EGL14.eglDestroyContext(eglDisplay, eglCtx);
EGL14.eglTerminate(eglDisplay);
return bitmap;
}

Define Size of the crop

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);

Text to Image in android

I am developing an application where I need to generate an Image from text and store that Image to the SDCard.
Can anyone tell me a library(just like textimagegenerator for java) I need android compatible library or source which I can use for this?
TextView textView = new TextView(activity.getContext());
textView.setText("Hello World");
textView.setDrawingCacheEnabled(true);
textView.destroyDrawingCache();
textView.buildDrawingCache();
Bitmap bitmap = getTransparentBitmapCopy(textView.getDrawingCache());
private Bitmap getTransparentBitmapCopy(Bitmap source)
{
int width = source.getWidth();
int height = source.getHeight();
Bitmap copy = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int[] pixels = new int[width * height];
source.getPixels(pixels, 0, width, 0, 0, width, height);
copy.setPixels(pixels, 0, width, 0, 0, width, height);
return copy;
}
You can use android.graphics.Canvas.drawText() for this.
Try to do this
Got the controls.
Button b1=(Button)findViewById(R.id.button1);
EditText ed1=(EditText)findViewById(R.id.editText1);
String msg=ed1.getText().toString();
Create the bitmap, canvas, paint,and invoke drawText function:
Bitmap bitmap = Bitmap.createBitmap(300, 400, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.CYAN);
Paint paint = new Paint();
paint.setTextAlign(Align.LEFT);// 若设置为center,则文本左半部分显示不全 paint.setColor(Color.RED);
paint.setAntiAlias(true);// 消除锯齿
paint.setTextSize(20);
canvas.drawText(msg, 20, 30, paint) ;
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
Save the image
String path = Environment.getExternalStorageDirectory() + "/abc.png";
FileOutputStream fos = new FileOutputStream(new File(path));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Assuming you have a text view or an image view, you will do this:
TextView tv = (TextView)findViewById(R.id.textview);
Bitmap bp;
bp = loadBitmapFromView(tv);
ImageView iv = new ImageView(this);
iv.setImageBitmap(bp);
try {
OutputStream fOut = null;
String path = "/sdcard/";
File file = new File(path, "imagename here.jpg");
fOut = new FileOutputStream(file);
getImageBitmap(bp).compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
} catch (Exception e) {
e.printStackTrace();
}
be sure to put this in your androidmanifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Yo can have a look at this "Android save view to jpg or png" post:
Hope this helps

How to crop an image in android? [duplicate]

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);

Categories

Resources