Reputation: 85
I am trying to encrypt an image in Android. What I would love to do is the following:
1. select image from gallery
2. convert image to byte array
3. encrypt the byte array
4. store the encrypted byte array as an image
5. retrieve the byte array from an encrypted image.
6. decrypt the byte array
7. restore the image
I have completed steps 1, 3 and 6. I have a problem with steps 2, 4, 5 and 7.
Original attempt:
// imgDecodableString is the String with the image file path
Bitmap imageBitmap = BitmapFactory.decodeFile(imgDecodableString);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
final byte[] byteArray = stream.toByteArray();
/* skip encryption/decryption for now */
Bitmap source = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Just doing the above returns the original image without problems.
However, I would like to store that encrypted byte array as an image. I planned to do +128 on each byte element (so that the range is 0..255 instead of -128..127) and create a new bitmap with RGB(byteArray[i],byteArray[i],byteArray[i]).
But there is a big problem... The size of the byte array that I get from compressing the image holds less elements than there are pixels in an image, which I guess what compression implies. With that being the case, I cannot create an image because the array size could be odd, and I need to preserve all of the bytes. So I tried the following:
// imgDecodableString is the String with the image file path
Bitmap imageBitmap = BitmapFactory.decodeFile(imgDecodableString);
ByteBuffer buffer = ByteBuffer.allocate(imageBitmap.getByteCount()); //Create a new buffer
imageBitmap.copyPixelsToBuffer(buffer); //Move the byte data to the buffer
final byte[] byteArray = buffer.array(); //Get the underlying array containing the data.
/* skip encryption/decryption for now */
Bitmap source = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
But now source is null...
Given a Bitmap, can I transform it into a byte array that has as many elements as the image has pixels (or a factor of)?
Upvotes: 0
Views: 1039
Reputation: 54781
The size of the byte array that I get from compressing the image holds less elements than there are pixels in an image, which I guess what compression implies. With that being the case, I cannot create an image because the array size could be odd, and I need to preserve all of the bytes.
I don't really see the problem other than your steps could do with a few changes:
Alternatively if you want to scramble the image, but keep it as an image, then I would avoid manipulating it as a byte array:
Upvotes: 1