Convert BufferedImage to aws...rekognition.model.Image - java

I'm playing around with the Amazon Rekognition. I found a really nice/easy library to take an image from my webcam which works like this:
BufferedImage bufImg = webcam.getImage();
I'm then trying to convert this BufferedImage to a com.amazonaws.services.rekognition.model.Image , which is what must be submitted to the Rekognition library. This is what I'm doing:
byte[] imgBytes = ((DataBufferByte) bufImg.getData().getDataBuffer()).getData();
ByteBuffer byteBuffer = ByteBuffer.wrap(imgBytes);
return new Image().withBytes(byteBuffer);
However when I try and do some API call to Rekognition with the Image, I get an Exception:
com.amazonaws.services.rekognition.model.InvalidImageFormatException: Invalid image encoding (Service: AmazonRekognition; Status Code: 400; Error Code: InvalidImageFormatException; Request ID: X)
The docs state that the Java SDK will automatically base64 encode the bytes. In case, something weird was happening, I tried base64 encoding the bytes before converting:
imgBytes = Base64.getEncoder().encode(imgBytes);
However, the same Exception ensues.
Any ideas? :)

I tried encoding the image to a JPG (Rekognition supports PNG or JPG formats) and it solved the problem.
BufferedImage bufImg = webcam.getImage();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufImg, "jpg", baos);
ByteBuffer byteBuffer = ByteBuffer.wrap(baos.toByteArray());
return new Image().withBytes(byteBuffer);

Related

How to pass an image from java to flutter?

I am trying to pass an image from java to flutter. The image is in bitmap in java so I first try to convert it to bytes[] using:
on java side:
int byteCount = transferredImage.getAllocationByteCount(); // transferredImage is the bitmap
ByteBuffer buffer = ByteBuffer.allocate(byteCount); //Create a new buffer
transferredImage.copyPixelsToBuffer(buffer);
byte[] myByte = buffer.array();
Then on flutter side I read the image as Uint8List and create an img.Image object from it:
img.Image styleImage = img.Image.fromBytes(
imgWidth,
imgHeight,
transferredBytes,
);
This works, without causing any errors but the image displayed using Image.memory(img.encodeJpg(styleImage)) always has a blue tint. The bitmap on java side is fine but when converted to bytes[] and displayed in flutter it has a blue tint..
So I assumed some important information may have been dropped during conversion to bytes using my above method, I then convert the image to an image format and then transfer the bytes:
at java side:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transferredImage.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte bytes []= baos.toByteArray();
on flutter side:
img.Image styleImage = img.Image.fromBytes(
imgWidth,
imgHeight,
transferredBytes,
);
But this does not work and creates an error:
RangeError (index): Index out of range: index should be less than
321512: 322560
If possible, I would prefer to have my first attempt work as it is really fast, so is there any way I can get this to work ?
Thanks

Saving Image Data in a "PNG" File in Java

Displaying an image in base64 is rather simple:
<img src="data:image/png;base64,hexadecimal-code-for-image-here">
However, what I'm trying to do is to convert the hexadecimal value received and the save it in a png file so I get the desired picture from the code.
For instance: let's say I have the following code:
iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABmJLR0QAAAAAAAD5
Q7t/AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3wEVDTYmJtINnAAAAcRJ
REFUOMuVlL9rU1EUx7/n3psmL6VoWqoJpNgI0Vg6uXSw0E0QHBzsUJDSoSKCuLro
KIL0D3Dr2N0gOHUpdWgrLW0EW5osakNT+4Oo7+X13XuPi4L2SZ73jGf43O/hfM4l
nKnC9TtZmStfIwKFn5bXW9vvDBxKnG2YdP7BzOzDtanp+6uBGLwFx1LxF7RtHvmI
tIaUsK7AWEJW6UgbC2MYxtjQFUijky/Hy5WROQIgBbgT6nyuUBo2hvGtVf8oVPrE
GCbDwM6Hjce71WcrXUfuv1C8lC9eHiMwlCCcGgs/1CBiFEuVShhZBKcGHQ309H0e
AtAd+PXwkFa36shkPCglIaXEcOE8jABqjQMQgEhrdAIfZCNKHFmlsr3C6yuzjaCD
tr56++m9GzfvPgEDr+efPzquVZco5QkhFcJ2cxuMoGtCHfk/EPkbvxsD+dJejyIA
jMzFkYZ+v7CJ8Pt/exrbMhFoaCCNYn8G2gpy9TTm4cF+U7xZ+QIAyHKbXD2NARtv
X7w6rk8sghmtrWrN1dPErbl6qpKArp4mAl09TRzZ1dPEhK6eKuff5JenzPinp87A
JE/JFZjyznm58sSVPzz96/R+AmVHLPIJpOvnAAAAAElFTkSuQmCC
Is there any way I can convert this code to image and then store in a png file in JAVA?
Transfer the base64 into byte array and than write it to a png file.
byte[] img = Base64.getDecoder().decode(imgBase64);
Files.write(Paths.get("my.png"), img); //As suggested by Joop Eggen
Decode base64 image to byte[] then using ImageIO to write to file
byte[] imgInBytes = Base64.getDecoder().decode(base64Img);
InputStream in = new ByteArrayInputStream(imgInBytes);
BufferedImage bufferedImage = ImageIO.read(in);
File png = new File("ImageAsPNG.png");
ImageIO.write(bufferedImage, "PNG", png);

Android - Error when uploading a bitmap to server C#

When i make upload of a image in Android to the server (C #) it generates an error converting the image to byte Array, this happens with some images which is very strange because this error is not always generated, that is, depending the image is correctly converted or not.
The conversion code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 50, stream);
final byte[] img_byte = stream.toByteArray();
final String imageString = Base64.encodeToString(img_byte, Base64.DEFAULT);
When receiving in C# I make the following conversion in the string, generating a byte Array and then for the MemoryStream.
byte[] novaFoto = Convert.FromBase64String(NovaFoto.FotoString);
using (MemoryStream stream = new MemoryStream(novaFoto))
{
Image image = Image.FromStream(stream);
}
depending at the image the error appears in either Convert.FromBase64String or Image.FromStream.
Can anyone help me with this? If you have another method i like this.Thanks!!

How to convert String to Image (Java)

I have an issue about my Application in detail.
- I have a java servlet receive data from mms gateway (MM7 protocol)
I get inputstream (image content , message content ) convert to string
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//String orgin = new String(byteArrayOutputStream.toByteArray(),"UTF-8");
String orgin = Streams.asString(request.getInputStream(), "ISO-8859-1");
Then I substring orgin for image content and convert to base64 and save to image file
but string that I convert to base64 can not save to image because this error
not a jpeg file
I print out string base64 does not start with /9j that mean not jpg format
please suggest or give an example for me
Best reqard
lieang noob noob
sorry for my english :)
This is at least part of your problem:
String orgin = Streams.asString(request.getInputStream(), "ISO-8859-1");
You shouldn't be converting it into a string to start with. It's binary data, right? So read it from the stream as binary data.
Now it sounds like you basically want to get separate "chunks" of that binary data - but converting the data into a string format to start with is not appropriate, unless that binary data really is encoded text.
I think, this might help: http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx
Encoding of image is very simple.
Encoding Source:
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Decoding Source:
byte[] decodedString;
decodedString = Base64.decode(picture, Base64.DEFAULT);
imageView1.setImageBitmap( BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length));
Use the below code the for the String to Image
here "origin" is a String
import org.apache.commons.codec.binary.Base64;
byte[] imgByteArray = Base64.decodeBase64(origin);
FileOutputStream imgOutFile = new FileOutputStream("C:\\Workspaces\\String_To_Image.jpg");
imgOutFile.write(imgByteArray);
imgOutFile.close();

Getting an in-memory representation of the JPEG rendering of an Image

I need to know how to get an array of bytes from a loaded image, in java. BufferedImage seems not to supply any methods that produce an array of bytes, so what do I use?
BufferedImage bufferedImage; //assumed that you have created it already
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage,"jpg", byteStream);
byte[] byteArray = byteStream.toByteArray();

Categories