Rotate bitmap image - android

Im taking a screenshot of my app and try to post it on facebook using the facebook SDK. But as the ShareDialog appears with the Image, it´s upside down.. So I need to re-rotate it.
This is how I create the image:
private void saveScreenshot() {
try{
FileHandle fh;
do{
fh = new FileHandle(Gdx.files.getLocalStoragePath() + "stoneIMG" + counter++ + ".png");
}while(fh.exists());
Pixmap pixmap = getScreenshot(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
PixmapIO.writePNG(fh, pixmap);
pixmap.dispose();
System.out.println(fh.toString());
}catch(Exception e) {
}
}
And here I fetch it:
private Pixmap getScreenshot(int x, int y, int w, int h, boolean yDown){
final Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(x, y, w, h);
if(yDown) {
ByteBuffer pixels = pixmap.getPixels();
int numBytes = w * h * 4;
byte[] lines = new byte[numBytes];
int numBytesPerLine = w * 4;
for (int i = 0; i < h; i++) {
pixels.position((h - i - 1) * numBytesPerLine);
pixels.get(lines, i * numBytesPerLine, numBytesPerLine);
}
pixels.clear();
pixels.put(lines);
}
return pixmap;
}
Then I try to share the photo:
public void sharePhoto() {
String filePath = Gdx.files.getLocalStoragePath() + "stoneIMG" + counter + ".png";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

If you want to rotate a bitmap by 180 degrees you can use this code:
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
Matrix matrix = new Matrix();
matrix.postRotate(180);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap , 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

Related

how to crop face from image in android

I want to crop face from image in android . After searching a lot in internet , I have come to know about this tutorial . I have an imageview .
iv1 = (ImageView) MainActivity.this.findViewById(R.id.img1);
When I tap this imageview I pick an image from Gallery . The code is as follows :
iv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
imgNo = 1;
}
});
In onActivityResult method , I am trying to crop face image according to the following code :
if (resultCode == RESULT_OK && imgNo == 1 )
{
selectedImage = imageReturnedIntent.getData();
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
yourSelectedImage = BitmapFactory.decodeStream(imageStream);
// iv1.setImageBitmap(yourSelectedImage);
path1 = selectedImage.getPath();
viewHeight = part2.getMeasuredHeight();
viewWidth = part2.getMeasuredWidth();
try {
Paint paint = new Paint();
paint.setFilterBitmap(true);
Bitmap bitmapOrg = yourSelectedImage;
int targetWidth = bitmapOrg.getWidth();
int targetHeight = bitmapOrg.getHeight();
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight, Bitmap.Config.ARGB_8888);
RectF rectf = new RectF(0, 0, viewWidth, viewHeight);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addRect(rectf, Path.Direction.CW);
canvas.clipPath(path);
canvas.drawBitmap(
bitmapOrg,
new Rect(0, 0, bitmapOrg.getWidth(), bitmapOrg
.getHeight()), new Rect(0, 0, targetWidth,
targetHeight), paint);
Matrix matrix = new Matrix();
matrix.postScale(1f, 1f);
BitmapFactory.Options bitmapFatoryOptions = new BitmapFactory.Options();
bitmapFatoryOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOrg = yourSelectedImage;
myFace = new FaceDetector.Face[5];
myFaceDetect = new FaceDetector(targetWidth, targetHeight,
5);
int numberOfFaceDetected = myFaceDetect.findFaces(
bitmapOrg, myFace);
Bitmap resizedBitmap = null;
if (numberOfFaceDetected > 0) {
PointF myMidPoint = null;
Face face = myFace[0];
myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance() + 20;
if (myMidPoint.x + viewWidth > targetWidth) {
while (myMidPoint.x + viewWidth > targetWidth) {
myMidPoint.x--;
}
}
if (myMidPoint.y + viewHeight > targetHeight) {
while (myMidPoint.y + viewHeight > targetHeight) {
myMidPoint.y--;
}
}
resizedBitmap = Bitmap.createBitmap(bitmapOrg,
(int) (myMidPoint.x - myEyesDistance),
(int) (myMidPoint.y - myEyesDistance),
viewWidth, viewHeight, matrix, true);
} else {
resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
viewWidth, viewHeight, matrix, true);
}
/* convert Bitmap to resource */
// Bitmap resizedBitmap = Bitmap.createBitmap(targetBitmap,
// 0,
// 0, viewWidth, viewHeight, matrix, true);
BitmapDrawable bd = new BitmapDrawable(resizedBitmap);
iv1.setImageBitmap(getCroppedBitmap(bd.getBitmap()));
} catch (Exception e) {
System.out.println("Error1 : " + e.getMessage()
+ e.toString());
}
iv1.invalidate();
}
But this code is not able to crop face from image picked from Gallery . How can I crop face from image ? Any advice is of great help .
You can try Facedetector built in class
FaceDetector.Face[] face=new FaceDetector.Face[20];
FaceDetector fd=new FaceDetector(200,200,2);
ImageView v=(ImageView)findViewById(R.id.imageView);
BitmapDrawable draw=(BitmapDrawable)v.getDrawable();
fd.findFaces(draw.getBitmap(), face);
//Now face will hold array face image

How to resize captured image before store in sdcard?

I am developing a application in which I want to resize captured image before store it in specified folder of sdcard.
I have used all the permissions required for write the data in sdcard but still I am unable to do it.
my code:
try{
Bitmap bitmap = Constant.decodeFile(fileName);
bitmap = Bitmap.createScaledBitmap(bitmap, 480, 320, true);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
File f = new File(fileName.toString());
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}catch (Exception e) {
e.printStackTrace();
}catch (OutOfMemoryError o) {
o.printStackTrace();
}
You have forgot to flush the Stream after writing data into into. use FileOutputStream.flush() after writing data... and
try this...
File file = new File(fileName.toString());
try {
FileOutputStream stream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, stream);
stream.flush();
stream.close();
} catch (Exception e) {
// TODO: handle exception
}
You can use createBitmap() to resize the original image.
FOllowing are the parameters:
(Bitmap source, int x, int y, int width, int height)
source The bitmap we are subsetting
x The x coordinate of the first pixel in source
y The y coordinate of the first pixel in source
width The number of pixels in each row
height The number of rows
Example:
Bitmap newbitmap = Bitmap.createBitmap(originalBitmap, 2, 2, bitmap.getWidth() - 4, bitmap.getHeight() - 120);
There is a nice tutorial on resizing images:
BitmapScaler scaler = new BitmapScaler(getResources(), R.drawable.moorwen, newWidth);
imageView.setImageBitmap(scaler.getScaled());
BitmapScaler class follows:
class BitmapScaler {
private static class Size {
int sample;
float scale;
}
private Bitmap scaled;
BitmapScaler(Resources resources, int resId, int newWidth)
throws IOException {
Size size = getRoughSize(resources, resId, newWidth);
roughScaleImage(resources, resId, size);
scaleImage(newWidth);
}
BitmapScaler(File file, int newWidth) throws IOException {
InputStream is = null;
try {
is = new FileInputStream(file);
Size size = getRoughSize(is, newWidth);
try {
is = new FileInputStream(file);
roughScaleImage(is, size);
scaleImage(newWidth);
} finally {
is.close();
}
} finally {
is.close();
}
}
BitmapScaler(AssetManager manager, String assetName, int newWidth)
throws IOException {
InputStream is = null;
try {
is = manager.open(assetName);
Size size = getRoughSize(is, newWidth);
try {
is = manager.open(assetName);
roughScaleImage(is, size);
scaleImage(newWidth);
} finally {
is.close();
}
} finally {
is.close();
}
}
Bitmap getScaled() {
return scaled;
}
private void scaleImage(int newWidth) {
int width = scaled.getWidth();
int height = scaled.getHeight();
float scaleWidth = ((float) newWidth) / width;
float ratio = ((float) scaled.getWidth()) / newWidth;
int newHeight = (int) (height / ratio);
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
scaled = Bitmap.createBitmap(scaled, 0, 0, width, height, matrix, true);
}
private void roughScaleImage(InputStream is, Size size) {
Matrix matrix = new Matrix();
matrix.postScale(size.scale, size.scale);
BitmapFactory.Options scaledOpts = new BitmapFactory.Options();
scaledOpts.inSampleSize = size.sample;
scaled = BitmapFactory.decodeStream(is, null, scaledOpts);
}
private void roughScaleImage(Resources resources, int resId, Size size) {
Matrix matrix = new Matrix();
matrix.postScale(size.scale, size.scale);
BitmapFactory.Options scaledOpts = new BitmapFactory.Options();
scaledOpts.inSampleSize = size.sample;
scaled = BitmapFactory.decodeResource(resources, resId, scaledOpts);
}
private Size getRoughSize(InputStream is, int newWidth) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, o);
Size size = getRoughSize(o.outWidth, o.outHeight, newWidth);
return size;
}
private Size getRoughSize(Resources resources, int resId, int newWidth) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeResource(resources, resId, o);
Size size = getRoughSize(o.outWidth, o.outHeight, newWidth);
return size;
}
private Size getRoughSize(int outWidth, int outHeight, int newWidth) {
Size size = new Size();
size.scale = outWidth / newWidth;
size.sample = 1;
int width = outWidth;
int height = outHeight;
int newHeight = (int) (outHeight / size.scale);
while (true) {
if (width / 2 < newWidth || height / 2 < newHeight) {
break;
}
width /= 2;
height /= 2;
size.sample *= 2;
}
return size;
}
}
http://zerocredibility.wordpress.com/2011/01/27/android-bitmap-scaling/
if you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your your image and use 0 instead of 100 in quality.
What's the problem exactly? Doesn't your code manage to open the file ? does it crash or have you just no error, but no output file?
By the way, you should call bitmap.recycle() at the end
It could help you harry
crop-image
BitmapFactory.Options optionsSignature = new BitmapFactory.Options();
final Bitmap bitmapSignature = BitmapFactory.decodeFile(
fileUriSignature.getPath(), optionsSignature);
Bitmap resizedSignature = Bitmap.createScaledBitmap(bitmapSignature, 256, 128, true);
signature.setImageBitmap(resizedSignature);

Facing Orientation issue with Camera captured image on Android phones

I am using exifInterface for photo rotation issue code is below: Facing captured image orientation issue from camera.
Create a Bitmap from the file
Bitmap b = BitmapFactory.decodeFile(imagePath);
Resize the Bitmap by scaling it to appropriate level
int width = b.getWidth();
int height = b.getHeight();
int newWidth = 150;
int newHeight = 150;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// Bitmap resizedBitmap = Bitmap.createBitmap(b, 0, 0, width, height, matrix, true);
// resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);
Handle orientation of the image
ExifInterface exif = new ExifInterface(imagePath);
String orientation = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
if (orientation.equals(ExifInterface.ORIENTATION_NORMAL)) {
// Do nothing. The original image is fine.
} else if (orientation.equals(ExifInterface.ORIENTATION_ROTATE_90+"")) {
matrix.postRotate(90);
} else if (orientation.equals(ExifInterface.ORIENTATION_ROTATE_180+"")) {
matrix.postRotate(180);
} else if (orientation.equals(ExifInterface.ORIENTATION_ROTATE_270+"")) {
matrix.postRotate(270);
}
Save the new bitmap
out = new FileOutputStream(new File("some output file path"));
Bitmap resizedBitmap = Bitmap.createBitmap(b, 0, 0, width, height, matrix, true);
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);
This code not working for resolve rotation issue, please give me guideline.
On Lg devices it's exifinterface always returning 0 orientation, Samsung devices returning 6 and 1.
How to fix this issue with all the devices like htc, Motorola, samsung , Sony and LG.
I am thankful to you all please help me.
You can use this function to do the same thing you require. Have this function in your activity or any util class and call it to get bitmap from file path.
I have been using this function in my application and my prime testing devices are LG.
public static Bitmap decodeFile(String path) {
int orientation;
try {
if (path == null) {
return null;
}
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 8;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bm = BitmapFactory.decodeFile(path, o2);
Bitmap bitmap = bm;
ExifInterface exif = new ExifInterface(path);
orientation = exif
.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == 3)) {
m.postRotate(180);
m.postScale((float) bm.getWidth(), (float) bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
return bitmap;
} else if (orientation == 6) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
return bitmap;
}
else if (orientation == 8) {
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
return bitmap;
}
return bitmap;
} catch (Exception e) {
}
return null;
}

How to resize Image in Android?

I am creating an application and want to setup a gallery view. I do not want the images in the gallery view to be full size. How do I resize images in Android?
Try:
Bitmap yourBitmap;
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);
or:
resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);
public Bitmap resizeBitmap(String photoPath, int targetW, int targetH) {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true; //Deprecated API 21
return BitmapFactory.decodeFile(photoPath, bmOptions);
}
Capture the image and resize it.
Bitmap image2 = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(image2);
String incident_ID = IncidentFormActivity.incident_id;
imagepath="/sdcard/RDMS/"+incident_ID+ x + ".PNG";
File file = new File(imagepath);
try {
double xFactor = 0;
double width = Double.valueOf(image2.getWidth());
Log.v("WIDTH", String.valueOf(width));
double height = Double.valueOf(image2.getHeight());
Log.v("height", String.valueOf(height));
if(width>height){
xFactor = 841/width;
}
else{
xFactor = 595/width;
}
Log.v("Nheight", String.valueOf(width*xFactor));
Log.v("Nweight", String.valueOf(height*xFactor));
int Nheight = (int) ((xFactor*height));
int NWidth =(int) (xFactor * width) ;
bm = Bitmap.createScaledBitmap( image2,NWidth, Nheight, true);
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bm.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
You can use Matrix to resize your camera image ....
BitmapFactory.Options options=new BitmapFactory.Options();
InputStream is = getContentResolver().openInputStream(currImageURI);
bm = BitmapFactory.decodeStream(is,null,options);
int Height = bm.getHeight();
int Width = bm.getWidth();
int newHeight = 300;
int newWidth = 300;
float scaleWidth = ((float) newWidth) / Width;
float scaleHeight = ((float) newHeight) / Height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0,Width, Height, matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
//photo is bitmap image
Bitmap btm00 = Utils.getResizedBitmap(photo, 200, 200);
setimage.setImageBitmap(btm00);
And in Utils class :
public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// RECREATE THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap;
}
bm = Bitmap.createScaledBitmap(bitmapSource, width, height, true);
:)
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=2; //try to decrease decoded image
Bitmap bitmap=BitmapFactory.decodeStream(is, null, options);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos); //compressed bitmap to file
Following is the function to resize bitmap by keeping the same Aspect Ratio. Here I have also written a detailed blog post on the topic to explain this method. Resize a Bitmap by Keeping the Same Aspect Ratio.
public static Bitmap resizeBitmap(Bitmap source, int maxLength) {
try {
if (source.getHeight() >= source.getWidth()) {
int targetHeight = maxLength;
if (source.getHeight() <= targetHeight) { // if image already smaller than the required height
return source;
}
double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
int targetWidth = (int) (targetHeight * aspectRatio);
Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
if (result != source) {
}
return result;
} else {
int targetWidth = maxLength;
if (source.getWidth() <= targetWidth) { // if image already smaller than the required height
return source;
}
double aspectRatio = ((double) source.getHeight()) / ((double) source.getWidth());
int targetHeight = (int) (targetWidth * aspectRatio);
Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
if (result != source) {
}
return result;
}
}
catch (Exception e)
{
return source;
}
}
resized = Bitmap.createScaledBitmap(yourImageBitmap,(int)(yourImageBitmap.getWidth()*0.9), (int)(yourBitmap.getHeight()*0.9), true);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 10;
FixBitmap = BitmapFactory.decodeFile(ImagePath, options);
//FixBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.gv);
byteArrayOutputStream = new ByteArrayOutputStream();
FixBitmap.compress(Bitmap.CompressFormat.JPEG, 80, byteArrayOutputStream); //compress to 50% of original image quality
byteArray = byteArrayOutputStream.toByteArray();
ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT);

Android 2.2 SDK - bitmap image resize nullPointerException

I'm loading images from URLS that are varying sizes. It seems the smaller ones come through, and a nullPointerException (displayed in the Log.d below) comes through for the larger ones. How can I get these images to resize?
BitmapDrawable drawable = null;
Bitmap bitmap = null;
try {
bitmap = loadBitmapFromWeb(url);
System.out.println("url " + url);
} catch (IOException e) {
}
int width = 150;
int height = 150;
try {
drawable = resizeImage(bitmap, height, width);
} catch (Exception e) {
Log.d("exception image", e.toString());
drawable = getDrawableFromResource(R.drawable.default_backup);
}
This is what I use to load from a URL:
public static Bitmap loadBitmapFromWeb(String url) throws IOException {
InputStream is = (InputStream) new URL(url).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}
This is what I use to resize, where the error appears:
public static BitmapDrawable resizeImage(Bitmap bitmap, int w, int h) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = w;
int newHeight = h;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
matrix, true);
return new BitmapDrawable(resizedBitmap);
}
Why don't you use available Bitmap function to do the resize. Supposing you downloaded correct image, you just need to do the following:
Bitmap scaledImage = Bitmap.createScaledBitmap(originalImage, newWidth, newHeight, false);

Categories

Resources