Introduction
Sometimes we will want to convert an image to a string, for example, store it in database or transfer it via XML. This post will show how to convert image to string/string to image.
The Program
ImageUtils.java
package test;
import java.io.IOException;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class ImageUtils {
/**
* Decode string to image
* @param imageString The string to decode
* @return decoded image
*/
public static BufferedImage decodeToImage(String imageString) {
BufferedImage image = null;
byte[] imageByte;
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
/**
* Encode image to string
* @param image The image to encode
* @param type jpeg, bmp, ...
* @return encoded string
*/
public static String encodeToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
public static void main (String args[]) throws IOException {
/* Test image to string and string to image start */
BufferedImage img = ImageIO.read(new File("files/img/TestImage.png"));
BufferedImage newImg;
String imgstr;
imgstr = encodeToString(img, "png");
System.out.println(imgstr);
newImg = decodeToImage(imgstr);
ImageIO.write(newImg, "png", new File("files/img/CopyOfTestImage.png"));
/* Test image to string and string to image finish */
}
}
Reference
Working with Images
http://docs.oracle.com/javase/tutorial/2d/images/index.html
Download
File at github
https://github.com/benbai123/JSP_Servlet_Practice/blob/master/Practice/JAVA/Commons/src/test/ImageUtils.java
Very Good!
ReplyDeleteThanks! :)
Deletewhere we dowanload in this jar sun.misc.BASE64Encoder
ReplyDeletesend the link this manil id
I use Alternate JRE (jre7) as JRE System Library then it works. But I think you can use any other Base64 Encoder/Decoder as needed.
DeleteAnd how i get Text in BufferedImage ?
ReplyDeletei make printScreen of text and how get it ?
thanks
DeleteWhat you need is an OCR tool for java (if you using java), refer to the thread at stackoverflow for more information
http://stackoverflow.com/questions/971344/java-based-ocr-sdk-api
how can i use this code on android ??
ReplyDeleteI am not familiar with android, probably you can use it directly or you need to find appropriate package/class accordingly.
DeleteFound some related articles at stackoverflow
http://stackoverflow.com/questions/7360403/base-64-encode-and-decode-example-code
http://stackoverflow.com/questions/4836760/how-to-use-base64-included-in-android-since-api-8-2-2-in-a-android-project-a
http://stackoverflow.com/questions/9768611/encode-and-decode-bitmap-object-in-base64-string-in-android
Really i am killed in scanning. Could you please help me. i will pay for your service.
ReplyDeletemy email id vbsenthilinnet@gmail.com
The problem is not with respect to payed or not, but I cannot help you without your environment (the scanning tool and its hardware/software accordingly), you should ask the vendor of that tool instead of me since what I can help is only ZK-related questions.
DeleteHello i am almost done. can you please give me hint after decoding how to show the image directly to ZK Image component without storing in the server cide
ReplyDeleteYou can change src of image with javascript:
Delete<image id="img" />
then
zk.Widget.$('$img').getImageNode().src = 'PATH_TO_IMAGE';
how if we want to convert an imageIcon to Base64 ? plz
ReplyDeletewhat is "imageIcon" here? actually you can convert any java Object to Base64 String if you can get an byte array from that object.
Deletewhat if we use byte array in our programs to store the images? can we just use getByteArray() methods with this to store it to database?
ReplyDeleteyes, you can store it in a BLOB column
Deletevery good!
ReplyDeleteThanks! :)
Deletethank u, very much useful ...
ReplyDeletethat's great! :)
Deleteuseful!
ReplyDeleteglad to hear that :D
DeleteHello Sir i used above code after getting byteString...I m trying to update in google Directory API...They Said invalid byteString
ReplyDeletehttps://developers.google.com/admin-sdk/directory/v1/reference/users/photos/update
above is url can u help me where i did wrong?
As mentioned in the document you need to convert the Base64 String to web-safe Base64, please refer to my testing strings (invalid and valid): https://gist.github.com/benbai123/a34bd1d5bdcf8037d831
Deleteyour string is valid...i also did same thing but string is not valid......my Code is
ReplyDeletepublic static byte[] encodeToString(BufferedImage image, String type) {
byte[] imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
Base64 encoder = new Base64();
imageString = encoder.encodeBase64(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
public static void main (String args[]) throws IOException {
BufferedImage img = ImageIO.read(new File("/home/user166/Firefox_wallpaper.png"));
BufferedImage newImg;
String imgstr = new String(encodeToString(img,"png"));
imgstr = imgstr.replace("/", "_");
imgstr = imgstr.replace("+", "-");
imgstr = imgstr.replace("=", "*");
System.out.println(imgstr);
}
If i removed * from that ecoded string then its working fine
DeleteCan you provide an image for testing?
DeleteSir it's Working fine......very helpful..Thanks
DeleteThat's great! :D
DeleteI would recommend against using Sun's internal proprietary API. I've modified your methods to use javax.xml.bind.DatatypeConverter instead:
ReplyDelete/**
* Decode string to image
* @param base64String The string to decode
* @return decoded image
*/
public static BufferedImage decodeToImage(String base64String) {
BufferedImage image = null;
byte[] imageByte;
try {
imageByte = DatatypeConverter.parseBase64Binary(base64String);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
} catch (Exception e) {
e.printStackTrace();
}
return image;
}
/**
* Encode image to string
* @param image The image to encode
* @param type jpeg, bmp, ...
* @return encoded string
*/
public static String encodeToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
imageString = DatatypeConverter.printBase64Binary(bos.toByteArray());
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
Thanks for your suggestion :)
DeleteCan't we get the string as output on the console?
ReplyDeleteyes you can, you can find "System.out.println(imgstr);" in the sample code above.
DeleteHi Ben,
ReplyDeleteAny sample code you have on "Convert PDF to Base64 String" ...
Yes, actually you can convert any type of file to string
Deletecode at pastebin: http://pastebin.com/QML4AMYV
Apache commons io: http://commons.apache.org/proper/commons-io/
Hey Ben,
DeleteBelow is my working code snippet..
/**
* Encode PDF to string
*
* @param filePath
*
* @return encoded string
* @throws IOException
*/
public static String encodePDFToString(String filePath) throws IOException {
System.out.println("I am in encodePDFToString...");
contenido = com.lowagie.text.pdf.codec.Base64.encodeFromFile(filePath);
return contenido;
}
Thanks so much.
ReplyDeleteYou're welcome! :D
DeleteExactly what I was looking for.... thanks!
ReplyDeleteThat's great! You're welcome :D
Deleteyou can try this free online service to convert image to base64 string and base64 to image.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteSorry for that. There are also online services to convert image to base64. Here is also a tutorial to convert base64 image to string and string to base64 image: http://javapointers.com/tutorial/java-convert-image-to-base64-string-and-base64-to-image/
DeleteAh...the code almost the same, but the date of that post is May 5, 2014.
DeleteWell, glad someone make one more entry :D
Really its great to see this kind of useful blog. Thanks for sharing this blog with us.
ReplyDeleteHow much does it cost to develop an On Demand Computer Technician Hiring App? The App Ideas is leading web and Mobile App development. We provide the best IT Services at best rates. Contact us now!