[Solved] Android equivalent to UIImageJPEGRepresentation?

I have a photo upload image widget in an iOS app that I am porting to Android. The data is sent as a HTTP POST in multipart/form-data format. I need to replicate this in Android but am having some problems.

Existing iOS code snippet:

if ([[dictionary objectForKey:key] isKindOfClass:[UIImage class]]) {
                        NSData *imageJPEG = UIImageJPEGRepresentation([dictionary objectForKey:key], 1);
                        NSString *filename = [NSString stringWithFormat:@"%@.jpg", key];
                        [(ASIFormDataRequest *)request setData:imageJPEG withFileName:filename andContentType:@"image/jpeg" forKey:key];

On Android I’m trying:

Bitmap fullImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
fullImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);

The resulting String is different for the same image on both platforms however, the result being that the Android image isn’t rendering on the server side after being uploaded.

What is the Android/Java Equivalent to UIImageJPEGRepresentation for converting an image to a byte array containing a jpeg-encoded image?

Enquirer: Sodman

Solution #1:

Make sure you’re setting the Content-Encoding HTTP header to base64 so the server knows to properly decode the base 64 back into a valid jpg.

Respondent: David Berry
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.