This question already has answers here:
How do I convert a byte array to Base64 in Java?
(4 answers)
Closed 1 year ago.
How can I convert an image like this one into a Base64 string?
I upload the image to the server with React, scale it, save it in the database, read it out again and get this format.
Now I have to convert this format into a Base64 format.
My Java Code to scale the image:
Part bild = request.getPart("bild");
InputStream in = null;
long fileSize = bild.getSize();
byte[] bytesBild = null;
if (fileSize > 0) {
in = bild.getInputStream();
BufferedImage imBuff = ImageIO.read(bild.getInputStream());
BufferedImage resize = resizeImage(imBuff, 200, 200);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(resize, "jpeg", os); // Passing: (RenderedImage im, String formatName, OutputStream
// output)
InputStream is = new ByteArrayInputStream(os.toByteArray());
bytesBild = IOUtils.toByteArray(is);
}
This is the result from my Database:
You could use the native java.util.Base64 class.
Save to database
//...
bytesBild = IOUtils.toByteArray(is);
String imgEncodedString = Base64.getEncoder().encodeToString(bytesBild);
//imgEncodedString --> ddbb
Read from database
byte[] imgDecodedBytes = Base64.getDecoder().decode(imgEncodedString);
ByteArrayInputStream bis = new ByteArrayInputStream(imgDecodedBytes);
//...
Related
My requirement is to convert the blob in a database field to string to create a json object. I have achieved that.
Now, I need to convert this string back to blob. I wrote the below code. But, it does not work. In my instance, I have the word document stored as blob. I converted it to string but when I converted the string to blob, the document does not open properly.
Please let me know a way to convert the string back to blob.
DocumentTemplateKey documentTemplateKey = new DocumentTemplateKey();
documentTemplateKey.documentTemplateID = "XX";
DocumentTemplateDtls documentTemplateDtls = DocumentTemplateFactory.newInstance().read(documentTemplateKey);
byte[] blobAsBytes = documentTemplateDtls.contents.copyBytes();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(blobAsBytes, 0, blobAsBytes.length);
String pdfBase64String =
org.apache.commons.codec.binary.StringUtils.newStringUtf8(org.apache.
commons.codec.binary.Base64.encodeBase64(bos.toByteArray()));
OutputStreamWriter out = new OutputStreamWriter(System.out);
JsonWriter writer = new JsonWriter(out);
//set indentation for pretty print
writer.setIndent("\t");
//start writing
writer.beginObject(); //{
writer.name("blob").value(pdfBase64String);
byte[] stringAsBytes = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(pdfBase64String);
Blob blob = new Blob(stringAsBytes);
documentTemplateDtls.contents = blob;
documentTemplateDtls.documentTemplateID = "XX12";
documentTemplateDtls.name = "XX12";
DocumentTemplateFactory.newInstance().insert(documentTemplateDtls);
writer.endObject();
writer.flush();
//close writer
writer.close();
Here's your problem:
byte[] stringAsBytes = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(pdfBase64String);
You're getting the bytes of your base64 string, but you ought to be putting it through a base64 decoder.
I have inserted a Base64 image to a database using this Java code:
FileInputStream mFileInputStream = new FileInputStream("C:\\basicsworkspace\\base64upload\\src\\main\\resources\\basic.png");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int bytesRead = 0;
while ((bytesRead = mFileInputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] ba = bos.toByteArray();
//byte[] encoded = Base64.getEncoder().encode(ba); // Util
byte[] encoded = Base64.encodeBase64(ba); // Apache
connection = DriverManager.getConnection(connectionString);
String insertSql = "INSERT INTO test (image) VALUES (?)" ;
prepsInsertProduct.setBytes(encoded);
System.out.println(insertSql);
prepsInsertProduct = connection.prepareStatement(insertSql);
System.out.println(prepsInsertProduct.execute());
But if I try to display the image in AngularJS using it, it is not displaying the image. In SQL Server I have saved my image as varbinary(max) and in AngularJS code,
config(function ($compileProvider) {
console.log($compileProvider.imgSrcSanitizationWhitelist());
})
<img src="choice:image/png;base64,{{choice.Icon}}">
But I am getting only bytes with a message like this:
unsafe:choice:image/png;base64,6956424F5277304B47676F414141414E535568455567…
Where am I going wrong? The image is in PNG format.
In POJO I made changes for byte[] and it worked. I have datatype with String and modified to byte[] but Base64 images didn't displayed but t is displaying only byte array images.
Try in your controller:
$scope.choice.Icon = 'data:image/jpeg;base64,' + yourImageData;
And in your HTML content:
<img ng-src="{{choice.Icon}}">
I am having trouble interpreting this question.
I receive a img in JSON formated in Base64, for web developers its only do:
"".
How I can make it in Java?
You can use apache commons-codec for converting byte array. to base64 and from base64 to byte array.
Actually, you can use guava. This artifact has base64 libraries and json.
Just add com.google.guava in your maven's project.
For creating image, you can use:
InputStream in = new ByteArrayInputStream(yourbytearray);
BufferedImage bImageFromConvert = ImageIO.read(in);
ImageIO.write(bImageFromConvert, "jpg", new File("c:/yourimage.jpg"));
//JSON funtion
String cmd_getPhoto = so.cmd_getPhoto();
//for remove ":"data:image\/png;base64,"
String imageDataBytes = cmd_getPhoto.substring(cmd_getPhoto.indexOf(",") + 1);
//for decode
Base64 b = new Base64();
byte[] decode = b.decode(imageDataBytes.getBytes());
//create the stream
InputStream stream = new ByteArrayInputStream(decode);
try {
//set the stream for a bufferedImage and do what your will with it
BufferedImage bitmap = ImageIO.read(stream);
jLabel6.setIcon(new ImageIcon(bitmap));
} catch (IOException ex) { }
I am trying to convert Image to Byte Array and save it in database. Image to Byte Conversion and bytes to Image Conversion using ImageIO Method works completely fine before saving it into database. But when i retrieve bytes from Database ImageIO returns null.
FileInputStream fis = new FileInputStream(picturePath);
BufferedImage image = ImageIO.read(new File(picturePath));
BufferedImage img = Scalr.resize(image, Scalr.Mode.FIT_EXACT, 124, 133, Scalr.OP_ANTIALIAS);
ByteArrayOutputStream ByteStream = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", ByteStream);
ByteStream.flush();
byte[] imageBytes = ByteStream.toByteArray();
ByteStream.close();
PersonImage = imageBytes;
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(PersonImage);
BufferedImage ImageForBox = ImageIO.read((InputStream)byteArrayInputStream);
PersonImageBox.setIcon(new ImageIcon((Image)ImageForBox));
Above code is what I do before saving picture bytes in DB. I resize the Image then convert it into bytes and then convert other way around and show it in JLabel, it works fine. But when I retrieve bytes from database and use the same code i.e.
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(PersonImage); // PersonImage are bytes from dB.
BufferedImage ImageForBox = ImageIO.read((InputStream)byteArrayInputStream);
PersonImageBox.setIcon(new ImageIcon((Image)ImageForBox));
In this case ImageIO returns null. Please help.
This is my code to convert image file into byte array.
public String GetQRCode() throws FileNotFoundException, IOException {
/*
* In this function the first part shows how to convert an image file to
* byte array. The second part of the code shows how to change byte array
* back to a image.
*/
AssetManager mgr = mAppView.getContext().getAssets();
InputStream in = mgr.open("www/Siemens_QR.jpg");
InputStreamReader isr = new InputStreamReader(in);
char[] buf = new char[20];
isr.read(buf, 0, 20);
isr.close();
// byte[] bytes = bos.toByteArray();
String abc = buf.toString();
return abc;
}
Here I am converting an image file into byte array. I am able to do this. But when try to read this image file using the path ("sdcard/Download/Siemens_QR.jpg") stored in emulator then I am getting VM aborting error. Please suggest me the correct path to read the image file stored in the emulator.
if you have jpg image stored on SD card then get the file path and try to convert the image to byte using following method...
Bitmap bitmap = BitmapFactory.decodeFile(file path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] byte_img_data = baos.toByteArray();