How to keep image quality same in BitmapFactory - android

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.

Related

Android: Efficient way to compress Bitmap

Is there a decent way to compress a Bitmap without re-scaling it without eating too much memory that cause OOM?
Bitmap compressedImageFile;
try {
compressedImageFile = MediaStore.Images.Media.getBitmap(getContentResolver(), fileUri);
//Converting bitmap to array stream
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//Decreasing the quality for thumbnail
compressedImageFile.compress(Bitmap.CompressFormat.PNG, 50, byteArrayOutputStream);
//Convert Bitmap to Byte array
byte[] thumbData = byteArrayOutputStream.toByteArray();
...
byteArrayOutputStream.toByteArray() is causing OOM, this can be avoid by reducing the bitmap size in a half but probably there is a more decent approach?
This is where I am using it

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.

Android: Attempting to Pass Bitmap as a Byte Array from One Activity to Another

I have been trying to pass a single byte array (compressed bitmap) from one activity to another. When I attempt to decode the byte array back to a bitmap, and show the bitmap, it appears to be a completely transparent bitmap.
I use this code on the first activity to compress the bitmap and send the byte array:
try {
InputStream selectedImage = getContentResolver().openInputStream(Uri.parse(photoPath));
bitmap = BitmapFactory.decodeStream(selectedImage);
} catch (FileNotFoundException exception) {
Log.e(this.toString(), exception.toString());
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte [] byteArray = stream.toByteArray();
Log.e("PANTHERIT_BYTEARRAY", byteArray.toString());
Intent stickerActivity = new Intent (this, StickerActivity.class);
stickerActivity.putExtra("byteArray", byteArray);
startActivity(stickerActivity);
And I use this code in the accepting activity to decompress and store the bitmap:
byte [] byteArray = getIntent().getByteArrayExtra("byteArray");
Log.e("STICKER_BYTEARRAY", byteArray.toString());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, options);
ImageView bitmapview = (ImageView) findViewById(R.id.bitmap_view);
bitmapview.setImageBitmap(bitmap);
I copied the code to the first activity, compressed the bitmap and immediately decompressed it. I took the decompressed bitmap and set it to an ImageView in that activity and it worked fine. So the error seems to be in the passing of the byte array from the first activity to the second, but I cannot figure out why that would be.
I found an answer. I do not really know why the byte array was getting messed up, maybe it was too large? Even so, both the input and output byte arrays were the same length, so not a very good explanation.
Anyway, I found my answer here: Send Bitmap Using Intent Android. The first answer by Zaid Daghestani is the same as what I initially tried, but his edit is what worked. Instead of passing a byte array, you save the compressed bitmap to a temporary file, and pass the filename through the intent. Definitely works for passing a bitmap, now I just have to figure out how to display the bitmap on a SurfaceView instead of an ImageView...
Also, just in case you need a mutable bitmap (in order to pass it to an ImageView) you can use:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
bitmap = BitmapFactory.decodeStream(input, null, options);

Convert PNG image to Base64

I am converting drawable resource png image to bitmap and then converting that bitmap to base64 and sending it to server by web service.
The image is stored on server at some address and in response i am getting URL where the image is stored.
The problem is after sending image to server the url which i am getting with that url i am setting image to other imageview but the transperent part of image is becoming black colored,
i think the problem is with converting png image to base64,
my code:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
bitmap = Bitmap.createScaledBitmap(bitmap, 300, 300, false);
mImageView.setImageBitmap(bitmap);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, bao);
byte[] ba = bao.toByteArray();
base64Image = Base64.encodeToString(ba, Base64.DEFAULT);
please give me solution ASAP
Everything you are doing seems right. Depending on the version of Android you are compiling with, decodeResource can have different default behavior. You can force the BitmapFactory to use an alpha channel when decoding with the following code.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inDither = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher, options);

Decode large base64 string

I have created a base64 string from a picture on the SD card using this(below) code, and it works but when I try to decode it (even further below) I get a java.lang.outOfMemoryException, presumably because I am not splitting the string into a reasonable size before I decode it as I am before I encode it.
byte fileContent[] = new byte[3000];
StringBuilder b = new StringBuilder();
try{
FileInputStream fin = new FileInputStream(sel);
while(fin.read(fileContent) >= 0) {
b.append(Base64.encodeToString(fileContent, Base64.DEFAULT));
}
}catch(IOException e){
}
The above code works well, but the problem comes when I try to decode the image with the following code;
byte[] imageAsBytes = Base64.decode(img.getBytes(), Base64.DEFAULT);
ImageView image = (ImageView)this.findViewById(R.id.ImageView);
image.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
);
I have tried this way too
byte[] b = Base64.decode(img, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
image.setImageBitmap(bitmap);
Now I assume that I need to split the string up into sections like my image encoding code, but I have no clue how to go about doing it.
You need decode the image in Background thread like AsyncTask
or
you need reduce your image quality using BitmapFactory .
Example:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inPurgeable=true;
Bitmap bm = BitmapFactory.decodeFile("Your image exact loaction",options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
You have two problem
base64 encoding requires much more space. 3 bytes convert to 4 chars (Factor 8/3)
you read the whole file at once
in same way your first approach solved this issues. So just use that version
By that way, why are you using decodeByteArray and not decodeFile
You might try to decode to a temporary file and create image from that file.
As to base64, it is 6 bits per character, or 6x4=24 bits=3 bytes per 4 characters.
So if you take 4 characters of base64, you will not break the corresponding 3 bytes.
That is, you may split the base64-encoded data at character indices that are a multiple of 4.

Categories

Resources