Converting images in Android - android

I am facing a few problems here. I have a socket server and my app uploads images to it. Now if I say I have 1 million customers each one 1mb for image, I should leave 1 terabyte for just profile images, which is too much. I am seeking a way to convert all image files to max 100 kb size, is such thing possible? If so what should I search for?
And also I'm selecting image files from disk, like this:
File file = new File("storage/sdcard/LifeMatePrivate/ProfileImage
/ProfileImage,imagechange_1,"+imagenamer+".jpg")
But as you see it just selects images with prefix.jpg. Is there a way I can the file with any extension? Thanks.
public void SaveImage(View v){
System.out.println(path);
String Path = path;
//File file=new File("storage/sdcard/Pictures/reza2.jpg");
Bitmap bitmap = BitmapFactory.decodeFile("storage/sdcard/Pictures
/reza2.jpg");
// you can change the format of you image compressed for what do you
want;
//now it is set up to 640 x 960;
Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 960, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// CompressFormat set up to JPG, you can change to PNG or whatever you
want;
bmpCompressed.compress(CompressFormat.PNG, 100, bos);
// Intent returnIntent = new Intent();
// returnIntent.putExtra("result",Path);
// setResult(RESULT_OK,returnIntent);
// Log.i("Image",path);
finish();
}
this code is inside an activity stared with StartActivityForResult

Try this to compress your images..
Bitmap bitmap = BitmapFactory.decodeFile(imagefilepath);
// you can change the format of you image compressed for what do you want;
//now it is set up to 640 x 960;
Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 960, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// CompressFormat set up to JPG, you can change to PNG or whatever you want;
bmpCompressed.compress(CompressFormat.JPEG, 100, bos);
now bmpCompressed is a compressed file format

There is 2 ways to scale a bitmap :
With given size :
Bitmap yourBitmap;
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);
Sampling image using :
BitmapFactory.decodeFile(file, options)

Related

Android: BitmapFactory changes dimensions of image when decoding from ByteArray

I am converting an android Image captured in my application to a bitmap. I am doing this by getting the image buffer from the pixel plane of the image and then using BitMapFactory to decode it into a Bitmap. However, doing so seems to change the resolution of the Image from 1920 x 1440 to 1800 x 1600, cropping out the top and bottom of the image in the process. The code for the method is shown here.
`protected void getImageFromBuffer(ImageReader reader){
Image image = null;
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
System.out.println("Getting Image Ready");
synchronized (this){
image_to_upload = new byte[buffer.capacity()];
buffer.get(image_to_upload);
Bitmap storedBitmap = BitmapFactory.decodeByteArray(image_to_upload, 0, image_to_upload.length, null);
Matrix mat = new Matrix();
mat.postRotate(jpegOrientation); // angle is the desired angle you wish to rotate
storedBitmap = Bitmap.createBitmap(storedBitmap, 0, 0, storedBitmap.getWidth(), storedBitmap.getHeight(), mat, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
storedBitmap.compress(Bitmap.CompressFormat.JPEG,70, byteArrayOutputStream);
image_to_upload = byteArrayOutputStream.toByteArray();
image_ready = true;
System.out.println("Image Ready");
}
}`
Debugging shows that the height and width of the Image are correct before the buffer is converted to a bitmap, but the bitmap dimensions are wrong immediately after decodeByteArray. Can anyone suggest why this may be? I have checked the dimensions before applying the matrix transformation.
EDIT: To add further details, I have tried using BitmapFactory.Options() to disable scaling or to set the target density and neither have any impact on the resulting Bitmap, it is always size 1800 x 1600.
You can change some options that affects the result resolution of your bitmap by using the Options param to the decodeByteArray:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDensity = DisplayMetrics.DENSITY_XXHIGH;//for example
BitmapFactory.decodeByteArray(image_to_upload, 0, image_to_upload.length, options);

Android Bitmap won't compress

I'm trying to compress a Bitmap which is taken from either the user's gallery or camera and store it as a profile picture in a Parse Server.
The issue is the bitmap will NOT compress. The image saves perfectly fine and is useable in the database, but the file size is massive for just a profile picture.
Here's my current code:
//Compressing
ByteArrayOutputStream stream = new ByteArrayOutputStream();
profilePictureBitmap.compress(Bitmap.CompressFormat.PNG, 20, stream);
byte[] image = stream.toByteArray();
//Saving
String imageName = username + "_profile_picture.png";
final ParseFile file = new ParseFile(imageName, image);
file.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e == null) {
user.put("profilePicture", file);
user.signUpInBackground();
}
}
}
I'm using a image picker library that gets the path of the image. I then turn it into a bitmap.
Heres my code to retrieve the image:
ArrayList<Image> images = data.getParcelableArrayListExtra(ImagePickerActivity.INTENT_EXTRA_SELECTED_IMAGES);
if(images.size() > 0) {
Image image = images.get(0);
File imgFile = new File(image.getPath());
if(imgFile.exists()){
profilePictureBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
profilePictureImage.setImageBitmap(profilePictureBitmap);
}
}
If there is any ideas on how to fix this I would greatly appreciate it.
Thanks :]
Image image = images.get(0);
File imgFile = new File(image.getPath());
if(imgFile.exists()){
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 2; // one quarter of original size
profilePictureBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), opts);
profilePictureImage.setImageBitmap(profilePictureBitmap);
}
Docs for inSampleSize:
If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory. The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. For example, inSampleSize == 4 returns an image that is 1/4 the width/height of the original, and 1/16 the number of pixels. Any value <= 1 is treated the same as 1. Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.

size of byte array before and after writing to file is different why

public void onPictureTaken(byte[] data, Camera camera) {
Uri imageFileUri = null;
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, bmpFactoryOptions);
Log.d("SIZE", "mBitmap size :" + data.length);
bmpFactoryOptions.inJustDecodeBounds = false;
mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, bmpFactoryOptions);
imageFileUri = getApplicationContext().getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS = getContentResolver().openOutputStream(imageFileUri);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageFileOS);
imageFileOS.flush();
imageFileOS.close();
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream1);
byte[] imageInByte1 = stream1.toByteArray();
long lengthbmp1 = imageInByte1.length;
Log.d("SIZE", "ByteArrayOutputStream1 size :" + lengthbmp1);
output of the Log is like below :
D/SIZE (23100): mBitmap size :4858755
D/SIZE (23100): ByteArrayOutputStream1 size :8931843
Can anybody help me why this difference.
I need to compress the image based on the size, but without compressing the size getting different..
You appear to be loading the image and then recompressing to bitmap
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream1);
Then you're wondering why the image size isn't the same? The answer is you've re-encoded it. Is 100 the compression ratio? If you load a bitmap compressed at 80% and then resave it to 100% in any image editor the size will grow.
The first question is why you reencode the bitmap when you already have the bytes. The size difference you observe comes from the different compression. The camera app will typically compress the image with a quality lower than 100 but you recompress it with 100. It is clear that your image representation will need more space.
If recompression is really necessary (for example if you altered the image in some way), try lower quality factors for better compression. Depending on your image something between 90 and 100 may work well.

Dynamically creating a compressed Bitmap

I'm writing a custom printing app in Android and I'm looking for ways to save on memory. I have three basic rectangles I need to print on a full page. Currently I'm creating a base Bitmap the size of the page:
_baseBitmap = Bitmap.createBitmap(width/_scale, height/_scale, Bitmap.Config.ARGB_8888);
The print process requests a Rect portion of that page. I cannot predetermine the dimensions of this Rect.
newBitmap = Bitmap.createBitmap(fullPageBitmap, rect.left/_scale, rect.top/_scale, rect.width()/_scale, rect.height()/_scale);
return Bitmap.createScaledBitmap(newBitmap, rect.width(), rect.height(), true);
Using bitmap config ARGB_8888 _baseBitmap is about 28MB (8.5"x11" # 300dpi = 2250*3300*4bytes). Even at 50% scaling (used above), my image is over 7MB. Scaling any smaller than this and image quality is too poor.
I've attempted to create _baseBitmap using Bitmap.Config.RGB_565, which does greatly reduce the full image size, but then when I overlay an image (jpegs) I get funny results. The image is compressed in width, duplicated next to itself, and all the color is green.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap myBitmap = BitmapFactory.decodeStream(input, null, options);
input.close();
return myBitmap;
....
private static Bitmap overlay(Bitmap bmp1, Bitmap bmp2, float left, float top) {
Canvas canvas = new Canvas(bmp1);
canvas.drawBitmap(bmp2, left, top, null);
return bmp1;
}
I know I can compress an image of these dimensions down to a reasonable size. I've looked into Bitmap.compress, but for some reason beyond my understanding I'm getting the same size image back:
ByteArrayOutputStream os = new ByteArrayOutputStream();
_baseBitmap.compress(Bitmap.CompressFormat.JPEG, 3, os);
byte[] array = os.toByteArray();
Bitmap newBitmap = BitmapFactory.decodeByteArray(array, 0, array.length);
_baseBitmap.getAllocationByteCount() == newBitmap.getAllocationByteCount()
It would be better to create it compressed than to create a large one and then compress it. Is there any way to create a compressed Bitmap? Any advice is greatly appreciated.
note: Not an Android expert. I'm not necessarily familiar with the platform specific terms you may use to respond. Please be gentle.
Try something like this, if you have a target size in mind.
private static final int MAX_BYTES_IMAGE = 4194304; // 4MB
//...
ByteArrayOutputStream out;
int quality = 90;
do
{
out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);
quality -= 10;
} while (out.size() > MAX_BYTES_IMAGE_FILESIZE);
out.close();

How to keep image quality same in BitmapFactory

I've converted an bitmap image into string to save it:
............
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
Then I retrieve the bitmap from string to set an activity's background just like that:
byte[] temp = Base64.decode(encodedImage, Base64.DEFAULT);
Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0,
temp.length, options);
Drawable d = new BitmapDrawable(getResources(), bitmap);
getWindow().setBackgroundDrawable(d);
Everything works fine but the image quality reduces tremendously. How can I keep the image quality same as the original image? Did I do something wrong here that have reduced the quality?
JPEG is lossy, no matter what quality settings you use. If you want to keep the image unchanged, you have to use lossless compression. for example Bitmap.CompressFormat.PNG
You are having here a tradeoff situation between picture quality and memory usage. Take a look at this line:
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
photo.compress is obviously decreasing your image resolution in a factor given by the second parameter, unfortunately, this is the best quality you can get, since between 0 - 100, 100 stands for the best quality you can get. Now, you have another option, depending on the original picture's size you can just save the image without compressing it, but be aware that most cases this doesn't work and Jalvik can throw an OutofMemoryException,
hope this helps.

Categories

Resources