?
Solved

Encode an image as a string using base64 encoding

Posted on 2007-10-10
43
Medium Priority
?
1,332 Views
Last Modified: 2008-02-26
Hi,

I need to encode a PNG image as a string using base64, but have had no luck finding out how to start. Hope you can help....anyone!

thanks in advance.
0
Comment
Question by:Rosscowie
  • 20
  • 12
  • 8
  • +1
42 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 20050256
     File f = new File("x.png");
      byte[] imageBytes = new byte[(int)f.length()];
      DataInputSteam in = new DataInputStream(new FileInputStream(f));
      in.readFully(imageBytes);
      in.close();
      byte[] encoded = new org.apache.commons.codec.binary.Base64().encode(imageBytes);
      StringBuilder sb = new StringBuilder(encoded.length);
      sb.append(imageBytes);
      String base64Image = sb.toString();


http://commons.apache.org/codec/
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20050294
If you need to be concerned about memory, read the image input stream into a buffer in a loop
0
 
LVL 13

Expert Comment

by:Bart Cremers
ID: 20051043
You can also use the Base64Encoder coming with the JRE instead of apache commons-codec:

... // read image bytes as posted above
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String base64Image = encoder.encode(imageBytes);
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Expert Comment

by:CEHJ
ID: 20051087
>>You can also use the Base64Encoder coming with the JRE

You can but the use of Sun proprietary classes is deprecated. If you use the Sun compiler you'll get something like

warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release

on compilation, a warning they mean you to take seriously.
0
 
LVL 13

Expert Comment

by:Bart Cremers
ID: 20051129
That's true, but the sun.misc classes tend to end up somewhere in the java or javax packages. And the Base64 classes are there since JDK 1.2 and have never been removed so far.

I would say, don't use the in production classes, but for toying around it's just easier to use them and don't go through the hassle of downloading extra jar files.
0
 
LVL 92

Expert Comment

by:objects
ID: 20052834
> And the Base64 classes are there since JDK 1.2 and have never been removed so far.

in fact *no* deprecated classes have been removed, and there is no plan to remove any of them so I wouldn't lose any sleep over it :)

There are also lots of simple implementations around (including source) to save importing an entire library into your code just for one simple function.

http://www.google.com/search?q=java+base64

Let me know if you need any help
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20054677
>>importing an entire library into your code just for one simple function.

Entire libraries *don't* get imported. Only classes that are used do. LIbraries are deployed with your code and the commons codec is in fact very small
0
 

Author Comment

by:Rosscowie
ID: 20055019
if there are doubts with the 2 methods you have described above, would using the javax.mail.internet.MimeUtility be useful? how would i be able to use this?

thanks for your help.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20055031
There are no doubts at all about using Commons codec. Are you already using javax.mail.*?
0
 

Author Comment

by:Rosscowie
ID: 20055053
yeah, and it would be handy if i could use this, i know there is an encode method passing in an outputstream that returns an outputstream but i then have trouble converting it into string / byte[]
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20055065
>>i know there is an encode method passing in an outputstream that returns an outputstream

Which one are you referring to?
0
 

Author Comment

by:Rosscowie
ID: 20055088
javax.mail.internet.MimeUtility

https://java.sun.com/products/javamail/javadocs/javax/mail/internet/MimeUtility.html

the encode method ive called it  as follows

byte[] byteArray = renderForm2(page177, strBackgroundPage, file177);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
baos1.write(byteArray);
OutputStream outStream = javax.mail.internet.MimeUtility.encode(baos1, "base64");

this renderfoem passes back a byteArray which i then need to encode using base64 and then create an encoded string.....

Thanks for helping
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20055097
In fact the situation is no different in JavaMail wit regard to proprietary Sun classes, but you could change the appropriate line in the code i posted to

byte[] encoded = com.sun.mail.util.BASE64EncoderStream.encode(imageBytes);
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20055104
Yes, your example would involve the class i mentioned but would be a better way of doing it
0
 

Author Comment

by:Rosscowie
ID: 20055107
its not the mail.util.*
 that i am alredy using it is the
javax.mail.*
0
 
LVL 92

Expert Comment

by:objects
ID: 20055130
> that returns an outputstream but i then have trouble converting it into string / byte[]

i see your using a ByteArrayOutputStream which will give you your byte array
you can then construct a String from that byte array.

String s = new String(baos1.toByteArray());

ps. specify a different string encoding f needed
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 1500 total points
ID: 20055132
byte[] byteArray = renderForm2(page177, strBackgroundPage, file177);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
OutputStream outStream = javax.mail.internet.MimeUtility.encode(baos1, "base64");
outStream.write(byteArray);
String encoded = new String(baos1.toByteArray());
0
 
LVL 92

Expert Comment

by:objects
ID: 20055135
> its not the mail.util.*

thats right, don't change it to use mail.util
what u have is the right way
0
 

Author Comment

by:Rosscowie
ID: 20055151
does that not mean that i will be writting over the encoded outputstream with the original byte array?

excuse me if im wrong but ive been messing with this for some while now and my head is mashed up, lol.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20055172
>>what u have is the right way

Not quite. What you need to do is to write to the OutputStream *returned* by the method. See my code
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20055176
>>does that not mean that i will be writting over the encoded outputstream

You will be writing *to* the stream that *provides* the encryption
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20055211
For me, with the code i posted, the 'Asker' image next to your name ( http://css.experts-exchange.com/xp/images/askerInfoColIcon.png ) produces

iVBORw0KGgoAAAANSUhEUgAAAFUAAABVCAMAAAAPK1hoAAAABGdBTUEAANbY1E9YMgAAABl0RVh0
U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAGAUExURfHx8URFRdm4l9zc3MijfIqLi/fD
bGxQL4hiPe3t7ZSUlaenp+y5Y+bHp5t3U+PXyOexWXd3dxARETIzM8yohKeCXWhnaNXCrzo7Oyss
LMTDw+np6dPT0/7co8vLy+Hh4fvXmLyYclZXVyIjI7S0tJNtR+Xl5bu7u9KtiaF8WPjuz8SVN9in
T8y6rKyHY8KeeY1nQZhyTP7hrNWykHBXPrGNZ/irhfXLg7aSbejGmLuONfHduHNgTfPs3rWklUg9
Lzc5OJyRddudteLUvS8xMVRJPtrNwJl+Y/Tx7fLb5Pjs8R8gIScoKDMwK86cPj84L0xMTPnSkVtc
XEFBQenBfO7q5Tg2
0
 
LVL 92

Expert Comment

by:objects
ID: 20055234
try this:

byte[] byteArray = renderForm2(page177, strBackgroundPage, file177);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
OutputStream outStream = javax.mail.internet.MimeUtility.encode(baos1, "base64");
outputStream.write(byteArray);
String s = new String(baos1.toByteArray(), "iso-8859-1");
0
 

Author Comment

by:Rosscowie
ID: 20055319
hi, im just trying the code just now, thanks! ill let you knwo how i get on...
0
 

Author Comment

by:Rosscowie
ID: 20055411
Works a treat! Thanks!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20055483
Rosscowie, can you explain why you accepted that answer which repeats code i'd already posted?
0
 

Author Comment

by:Rosscowie
ID: 20055597
sorry CEHJ i though i had marked what you had put!

how can i change this? i didnt realies that it was someone else who posted!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20055621
Don't worry. Do nothing yet - i'll get the q reopened
0
 
LVL 92

Expert Comment

by:objects
ID: 20055653

the only similiarity is that they do base64 encoding (which is what ythe q is about so thats no surprise), yours though needs an entire 3rd party library to be unnecessarily used.
re-read the code to see :)
0
 
LVL 92

Expert Comment

by:objects
ID: 20055661
suggesting what I posted repeats what was already posted is ridiciulous.
0
 
LVL 92

Expert Comment

by:objects
ID: 20055729
if u want to award CEHJ points then tahs fine but its definitely not how this site works.
The code CEHJ posted did not answer your q, as shown by the numerous follow up questions (and replies that also didn't help answer your question). Plus it seemed pretty clear you didn't want to use a 3rd party lib which he simply ignored.
The code I posted did answer your question, and is in no way repeating what CEHJ posted. As such how you closed the question correctly, thats how EE works :)
0
 

Author Comment

by:Rosscowie
ID: 20055765
objects:
byte[] byteArray = renderForm2(page177, strBackgroundPage, file177);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
OutputStream outStream = javax.mail.internet.MimeUtility.encode(baos1, "base64");
outputStream.write(byteArray);
String s = new String(baos1.toByteArray(), "iso-8859-1");

CEHJ:
byte[] byteArray = renderForm2(page177, strBackgroundPage, file177);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
OutputStream outStream = javax.mail.internet.MimeUtility.encode(baos1, "base64");
outStream.write(byteArray);
String encoded = new String(baos1.toByteArray());

all objects has added is: "iso-8859-1"

the follow up questions are regarding how the codee works writing data to the output stream if you wish to read correctly.

Before with object all you suggestion would be to search google, how does that help, that is not how EE works, it works by awarding the points to the person who has helped you the most in given the correct answer. The sugestion CEHJ made was not using a 3rd party.
0
 
LVL 92

Expert Comment

by:objects
ID: 20055819
The code he posted was just repeating what you, and I had already posted :D

> String encoded = new String(baos1.toByteArray());
> all objects has added is: "iso-8859-1"

See my earlier comment, that line was copied from my comment.

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20055826
>>all objects has added is: "iso-8859-1"

(which is actually superfluous for 7-bit ascii characters)
0
 

Author Comment

by:Rosscowie
ID: 20056419
I ahve a question for the two of you?

Why is it then, that no matter whos method i try now when i encode my image and print out the string the sirst part of the string seems not to be encoded and the other part is?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20056447
What makes you think that?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20056454
Please post an example (small file please ;-)) like i did
0
 

Author Comment

by:Rosscowie
ID: 20056820
Because it starts off like this..........  
IHDR  ¼  Þ   a?^ñ    IDATxÚíÝ
?¥Yzöwºª§{z>wwfvwÖöÚ`[Ȭ¾lÅA? c?IØ? Y°-äDH8
"È?%H FX!

?±&Ù( ?½?í;Â`Ų³8ì²ëõÇxv==;===Ýu{r\ÏÜÿ>uÞê?ÙùØ?­÷÷ÓèêÖ­[·ªÞê¹ïÿ}Î9Ϲã?^X  ^Ê9?    ¡   ¡   ¡ @h  ? @h  ? @h  ? @h    ¡   ¡   ¡   ? @h  ? @h  ? @h  ?  ¡   ¡   ¡   ¡ @h  ? @h  ? @h  ? @h    ¡   ¡   ¡   ? @h  ? @h  ? @h  ?  ¡   ¡   ¡   ¡ @h  ? @h  ? @h  ? @h    ¡   ¡   ¡   ? @h  ? @h  ? @h  ?  ¡   ¡   ¡   ¡ @h  ? @h  ? @h  ? @h    ¡   ¡   ¡   ? @h  ? @h  ? @h  ?  ¡   ¡   ¡   ¡ @h  ? @h  ? @h  ? @h    ¡   ¡   ¡   ? @h  ? @h  ? @h  ?  ¡   ¡   ¡   ¡ @h  ? @h  ? @h  ? @h    ¡   ¡   ¡   ? @h  ? @h  ? @h  ?  ¡   ¡   ¡   ¡ @h  ? @h  ? @h  ? @h    ¡   ¡   ¡   ? @h  ? @h  ? @h  ¶êÐ! ^?^x!÷ï¸ã??nÞ¼?Û?Ft¸cOz ¡Ø®?*%ìv»??úÔÁÁÁ
çÎ?«Ûz²è BpfcÁ ǪrÐÇêþÈ
GGG7?ݸqc<Xéa¤??cwÞyç¸=<<¬ !4?Ð ??²Aî§`ps/¢äñ®]»6Ãõë×???G8Aá®»îºûî»/^¼8îTz¨üá??Ð |vä??êì?ÄÐÓÀn·?Tñ ?Á0?<n«?0??0?0yî¹ç?þùg?}öêÕ«ã?zÙî»ï¾xàMozÓý÷ßï½÷?Üpþüù°ð? ¡xãªP%?:ë×?Ê
}RBE??? ÆgG,¨GvÇÆ?ã?q{íÚµg?yfä??®\¹Rõ?? FhxË[Þò?w¼ã?G©À1rC%¡?à?UQXÚ(Ã8Í'?Û:µ×??
??0¹¾W%?º?1??u|v<>?öì±

ãÕF,¸xñâC=ôøã??01^öàààüùó5ÑÁ 
Àg Ô?q®:Árréc¥?$?*T¨ÓÝ?ç?Ç+
#?'Ô?ø­&*sÔ?zÁ<§^¤rÉ? Fb¯0~?;ï¼óÒ±ñ`?Pøó?Ð ¼^i ?òàzvB?­û(C
C$"T=`|ø?O|¢ÎñI      
5/a<R?!õ?úìn¯^¼*I?îP¥?ñâã'¹ûî»ßò?·<ôÐCãv¼ÚÅ?ý?Ah ^a,ȹi
??Ø¿*Ösê²~\¸×u
@ÔY¼Îëuú¿vl¤???zê©g?yæÊ?+W?eÖ¸Í$?
?êER?¨o±´¹¹_?¡¦,Ttic|»Çüãÿø?)õíÆK? ¡¸]Á ßé)a9¹Ä1'ã:I?söøªq?ÏÖ)¼>? PúU3¨y?U`¨RAM8gî§?~zܹ¡*
?2¹¡?e$(¤xP?óx¤Æz ??=êçߢ¾Ý¸­©?Å
°é|0?;{è ¦VãÜ?¯ªSx?ª3¸?³xÎå9£×i¸?/TV¨Q?Z 9?Ï?ûtÅzN^³?ËÉù?NêìÞ[<e(¤~æ>?2?Ük'õ?ÔRÌ¡~BÿZ@h?-F??>û#S&¨jÁ8m×rªî«ÒT±FªlP?W© ??ZÂÑ^?2Ä?e??«Xë³õ?ú0+-û??÷«TPOÈ#?O?;VÏ?·WÖo?LE¤/ÓHõÅ¿%àLUN-¿çNe? *ôöGj?@&$
?ç?÷ÜsUTÈì?º"¯N??fXVhH·¥ôT¨Ûä??¤O-ZT·rþ®Q?üîÕ
zÙï"QÏÉýþau_¨ï5~Ϊ[T?H~ªt²Ø~?øìJËÉ?%§Ï?
?6¸Ðg faB?ê\'ûõ¹¿.úû?Å:©×#uÑ_gú ª¨??ÊÄÆ?øûÜÃ\ÁgØ"ñeÙ?5?j²?|P§ð +ôÍ¥êÎááḭE?µDE?ܯ'?'gúB?}qGfB       4À´`?~É}<~:«M»5f-À´'S&d?a_¤Pçû?F??Y??¥
?z>¨WKa µ?úFË~¡Ä²??
ãõ?ñáøÂñÌ?ǪÀ0T¢?S?ví"1rÒ'>ñ?ñ»?¯?%?}$húûú?øä=Ó½òߣC?Òê?Ú«ë¹Úî×Ö¹?µ¢?Ü

Then half way through its format changes to this....

ej53d2Z2d9b22mBbyKwVEr5sxUGLAGOQSdgYEpAMWbAt5ERIOAoiyIolSAxGWCEKCoqxESbZKBAL
jL0GjO0EEzvCYMURsrM47LLr9cd4dj0fPTs9PT3ddXtyXM/c/z513uqe2fnYna3399Po6tatW7eq
3uq57/99zjnPueOFF15YAABeyjmHAAAQGgAAoQEAEBoAAKEBABAaAAChAQBAaAAAhAYAQGgAAIQG
AEBoAACEBgBAaAAAEBoAAKEBABAaAAChAQAQGgAAoQEAEBoAAIQGAEBoAACEBgBAaAAAhAYAQGgA
AIQGAAChAQAQGgAAoQEAEBoAAKEBABAaAAChAQBAaAAAhAYAQGgAAIQGAEBoAACEBgBAaAAAEBoA
AKEBABAaAAChAQAQGgAAoQEAEBoAAIQGAEBoAACEBgBAaAAAhAYAQGgAAIQGAAChAQAQGgAAoQEA
EBoAAKEBABAaAAChAQBAaAAAhAYAQGgAAIQGAEBoAACEBgBAaAAAEBoAAKEBABAaAAChAQAQGgAA
oQEAEBoAAIQGAEBoAACEBgBAaAAAhAYAQGgAAIQGAAChAQAQGgAAoQEAEBoAAKEBABAaAAChAQBA
aAAAhAYAQGgAAIQGAEBoAACEBgBAaAAAEBoAAKEBABAaAAChAQAQGgAAoQEAEBoAAIQGAEBoAACE
BgBAaAAAhAYAQGgAAIQGAAChAQAQGgAAoQEAEBoAAKEBABAaAAChAQBAaAAAhAYAQGgAAIQGAEBo
AACEBgBAaAAAEBoAAKEBABAaAAChAQAQGgAAoQEAEBoAAIQGAEBoAACEBgBAaAAAhAYAQGgAAIQG
AAChAQAQGgAAoQEAEBoAAKEBABAaAAChAQBAaAAAhAYAQGgAAI


It is jibberish lol but its the format and when i encode the same image on an online encoder it is different to the start
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20057477
You should close the OutputStream - did you?
0
 

Author Comment

by:Rosscowie
ID: 20057702
no that must have been the problem. thanks
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20057725
No problem
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 20230848
:-)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month15 days, 10 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question