changeing image file resoultion in android - android

i am saving a captured image in sdcard by using following code
class SavePhotoTask extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... jpeg) {
File photo=new File(Environment.getExternalStorageDirectory(),"photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos=new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
}
catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
return(null);
}
}
but i am getting the image of resolution 1024*768 how can i change the resoultion of that image.
i am calling SavePhotoTask like this
Camera.PictureCallback photoCallback=new Camera.PictureCallback(){
public void onPictureTaken(byte[] data, Camera camera){
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawBitmap(itembmp,left,right,null);
image.setImageBitmap(mutableBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mutableBitmap.compress(Bitmap.CompressFormat.PNG,100, stream);
byte[] byteArray = stream.toByteArray();
new SavePhotoTask().execute(byteArray);
Toast.makeText(PreviewDemo1.this,"Image Saved",Toast.LENGTH_LONG).show();
camera.startPreview();
inPreview=true;
}
};
thanks in advance

It is the jpeg passed to the doInBackground method that already has that resolution - you need to change whatever is calling this code.

If you can parse it to BitMap then you can use this:
private final int MAX_WIDTH = 400;
private final int MAX_HEIGHT = 400;
public Bitmap getResizedBitmap(Bitmap bm) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth;
float scaleHeight;
if (width < MAX_WIDTH && height < MAX_HEIGHT) {
return bm;
}
if (width > height) {
scaleWidth = ((float) MAX_WIDTH) / width;
scaleHeight = ((float) MAX_HEIGHT * height / width) / height;
} else {
scaleWidth = ((float) MAX_WIDTH * width / height) / width;
scaleHeight = ((float) MAX_HEIGHT) / height;
}
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap;
}

Related

How to generate proper scaled bitmap to upload that to server faster?

Currently I'm using mulitpart/form-data for uploading images to server . In node.js server side the images are being stored without any problem . But it's taking a lot of time to upload the pictures to server . I tried to rescale bitmaps before uploading them but in most of the cases pictures are being uploaded in a larger size than the original image for ex- 200kb pic is becoming 400kb something like that . So, I wonder How to scale bitmaps properly and upload them to server in good quality with efficient speed ?
Bitmap Scaling Code:
bmp = MediaStore.Images.Media.getBitmap(ctx.getContentResolver(), uri);
int maxSize=700;
int outWidth;
int outHeight;
int inWidth = bmp.getWidth();
int inHeight = bmp.getHeight();
if(inWidth > inHeight){
outWidth = maxSize;
outHeight = (inHeight * maxSize) / inWidth;
} else {
outHeight = maxSize;
outWidth = (inWidth * maxSize) / inHeight;
}
final Bitmap new_bitmap = Bitmap.createScaledBitmap(bmp, outWidth, outHeight, false);
Saving Bitmap to storage:
void saveImage(String imgName, Bitmap bm) throws IOException {
//Create Path to save Image
File file_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/Infinity"); //Creates app specific folder
file_path.mkdirs();
File imageFile = new File(file_path, imgName + ".png"); // Imagename.png
FileOutputStream out = new FileOutputStream(imageFile);
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
out.flush();
out.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(ctx, new String[]{imageFile.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String pathi, Uri uri) {
Log.i("ExternalStorage", "Scanned " + file_path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
parts.add(prepareFilePart("photo", pathi));
RequestBody description = createPartFromString(obji.toString());
FileUploadService service = ServiceGenerator.createService(FileUploadService.class);
Call<ResponseBody> call = service.uploadMultipleFilesDynamic(description, parts);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v("Upload", "success");
Intent i=new Intent(ctx,Home_Screen.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(i);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
if(t.getMessage()!=null) {
Log.e("Upload error:", t.getMessage());
Toast.makeText(ctx, t.getMessage(), Toast.LENGTH_LONG).show();
//Don't toast t.getMessage it would show the ip address which is bad
}
}
});
//Toast.makeText(ctx, "Downloaded Successfully", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
throw new IOException();
}
}
Try this, it's a working solution.
private uploadPostImage(String imagePath) throws Exception {
String orientation = "Portrait";
Bitmap bm = null;
try {
bm = checkForRotation(imagePath);
if (bm.getHeight() > bm.getWidth()) {
orientation = "Portrait";
} else if (bm.getWidth() > bm.getHeight()) {
orientation = "Landscape";
} else {
orientation = "Portrait";
}
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
if(bm.getWidth()>1000)
{
bm = getResizedBitmap(bm,1000);
}
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
/*
/....
Multipart uploading work
..../
*/
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
}
public Bitmap checkForRotation(String filename) {
Bitmap bitmap = BitmapFactory.decodeFile(filename);
int tmpHeight, tmpWidth;
tmpWidth = bitmap.getWidth();
tmpHeight = bitmap.getHeight();
if (tmpWidth > tmpHeight)
{
tmpWidth = 1000;
tmpHeight = (bitmap.getHeight() * tmpWidth) / bitmap.getWidth();
} else
{
tmpHeight = 1000;
tmpWidth = (bitmap.getWidth() * tmpHeight) / bitmap.getHeight();
}
bitmap= Bitmap.createScaledBitmap(bitmap, tmpWidth, tmpHeight, true);
ExifInterface ei = null;
try {
ei = new ExifInterface(filename);
new ExifInterface(filename);
} catch (IOException e) {
e.printStackTrace();
}
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
bitmap = rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
bitmap = rotateImage(bitmap, 180);
break;
}
return bitmap;
}
public Bitmap getResizedBitmap(Bitmap bm, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float ratio = (float)width/(float)height;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float)newWidth/ratio) / height;
// CREATE A MATRIX FOR THE MANIPULATION
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;
}
Here is a method to compress the image. First send the path of the image you want to compress to this method. It will return you the compress image path, then make a file from that path and upload.
public static String compressImage(String filePath) {
try {
//String filePath = getRealPathFromURI(imageUri);
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
//by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//you try the use the bitmap here, you will get null.
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
//max Height and width values of the compressed image is taken as 816x612
float maxHeight = 816.0f;
float maxWidth = 612.0f;
float imgRatio = actualWidth / actualHeight;
float maxRatio = maxWidth / maxHeight;
//width and height values are set maintaining the aspect ratio of the image
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
//setting inSampleSize value allows to load a scaled down version of the original image
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
//inJustDecodeBounds set to false to load the actual bitmap
options.inJustDecodeBounds = false;
//this options allow android to claim the bitmap memory if it runs low on memory
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
//load the bitmap from its path
bmp = BitmapFactory.decodeFile(filePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
//check the rotation of the image and display it properly
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Log.d("EXIF", "Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 3) {
matrix.postRotate(180);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 8) {
matrix.postRotate(270);
Log.d("EXIF", "Exif: " + orientation);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out = null;
//String filename = getFilename();
String filename = getFilename();
try {
out = new FileOutputStream(filename);
//write the compressed bitmap at the destination specified by filename.
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return filename;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
use multipart to upload images with retrofit instead of any other network library.
How to make images upload faster in an Android app?

poor image quality after saving rotated bitmap to sdcard

I am making an app where in one of the activity i am fetching image from gallery and showing it in adapter like image below
I have to rotate that image and save it to sdcard. My code is doing fine but after saving it to sdcard i get very poor quality of image. my code is:
viewHolder.imgViewRotate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imagePosition = (Integer) v.getTag();
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
try {
FileOutputStream out = new FileOutputStream(new File(uriList.get(rotatePosition).toString()));
rotated.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
});
Any suggestions will be great help.
Try out below code to reduce image size without losing its quality:
public 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;
// create a matrix for the manipulation
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;
}
EDITED:
Resize the image using BitmapFactory inSampleSize option and the image doesn't lose quality at all. Code:
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bm = BitmapFactory.decodeFile(tempDir+"/"+photo1_path , bmpFactoryOptions);
int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)600);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)800);
if (heightRatio > 1 || widthRatio > 1)
{
if (heightRatio > widthRatio){
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(tempDir+"/"+photo1_path, bmpFactoryOptions);
// recreate the new Bitmap
src = Bitmap.createBitmap(bm, 0, 0,bm.getWidth(), bm.getHeight(), matrix, true);
src.compress(Bitmap.CompressFormat.PNG, 100, out);

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

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