How to build base64 image src with jsp source? - java

I am struggling with base64.
I would like to decode an image which comes though wysiwyg editor.
I build a source like below.(it is part of...)
InputStream is = request.getInputStream();
byte b[] = IOUtils.toByteArray(is);
String base64DataString = Base64.encodeBase64String(b);
String aaa = Base64.encodeBase64URLSafeString(b);
base64DataString = "data:image/" + ext + ";base64," + aaa;
if(aaa == "a"){}
if(is != null) {
is.close();
}
I got InputStream from request and make it as byte array.
size of byte[] b is exactly same with size of file I uploaded.
Then I combine a String to put src attribute of image tag.
After all of this when I look at in HTML. It has a broken image.
output looks like below :
<img src="data:image/jpeg;base64,_9j_4AAQSkZJRgABAQAAAQABAAD_2wCEAAkGBhQSERQUExQWFRUWGBgaGRgYFxwcGBwYFxwcGxgYGxoaHSYfHRwjGhUYHy8gIycpLCwsGB8xNTAqNSYrLCkBCQoKDgwOGg8PGi0kHyQsLCwsLCwuLCwsLywsLCwsLCwsLCwsLCwsLCksLCwsLCwsLCwsLCwsLCwsLCwsLCwsLP_AABEIAMIBAwMBIgACEQEDEQH_xAAcAAACAgMBAQAAAAAAAAAAAAAEBQMGAAECBwj_xABJEAABAwIDBAcDCAgDBwUAAAABAgMRACEEEjEFQVFhBhMicYGRoTKxwQcUQlJigtHwIzNykqKy0uEWc_EVNENEY5PCFyRTg6T_xAAbAQADAQEBAQEAAAAAAAAAAAACAwQBAAUGB__EADERAAIBAwMCBAQGAwEBAAAAAAABAgMRIRIxQRNRBCJhkXGhsfAFFFKB4fEyQtHBkv_aAAwDAQACEQMRAD8A3imEtCxPcEonzT8aru2GsOtehJt9Ig-QNAu4JeoQV8ogeakfGmOA7ABWyhs8S7J8gLeZqmThPl__ACUpSh8fiALwa0x83UUAi4OY-9UCjcF0cdVBUQeXVie_MVKNMBjmVHWD3qM92-abr24UtpCUrA49YNO6bd1ap6VdLHxaAnd4e_wK-90fcT2VqvwEDzkisZ2AsqAJWgcg3-Bo9_aSlG2bvzg_A1A5h3nDJYUsDVQQkGOZUUiuVVTd7fO52lwVr2_YXbb2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7qG7GJIrbuyM11Eqjj8NwpbjOija57Nz4e6rsHERMihOvSJ9KJVJHaCfov0k6ppLGI7OVICHPoqyiBm-qqONjFjeKcDHpJsQQd4uPOkJdQoCbWtIgxxvuPupa_g0oOZtRQfsmAe8aHxFNjLuieVHOC9tYtMXrheLF71S2tpPDehXeCPcYqN7aOIVopCO4Sf4p91H5QenMuTmOFKsX0qZRILgJ4DtHyTNVksqcHbcUrkTbyECto2ekaeVC7INU3yxoemyCbIcV92PeRUa-mwH_AAnP4f6qXnBAGwFYvBgisduwxQXcJPTn_oufvI_qrKCGBHKsoL-gWmPc9SaSOFEpSKysr6NnykSdKRwrMg4CsrKEMzKOFclA4CsrKwwzIOArZbE6DdurdZWM1ETzYtYacKXLaF7DXhWVlYjXubS2OA8q7WkcKyspMimGwMtInStpTWVlCwjoisArKyhNR1lHCsyDgKysoGGjZaHAeVDPMpnQacKysoeQrgbzCfqjyFCqZTwHlWqyhaGxbIHGk8B5d1CuNi1hod1ZWUKQ1MFxDQgCBEcKExDKfqjyFZWVj3GJnDKYmOFRLF_zyrdZQ8lHARFvvD3VpSjfvHurKyuFAylmdTpWs5jU1lZRoxirFPqzntHzNbrKylmn_9k
" title="gaebul.jpeg">
What is the suspicious part of my code?
Thanks for sweet answer :D bb

You seem to be encoding two times without the real need, you should just do
byte[] encodeBase64 = Base64.encodeBase64(b);
String base64DataString = new String(encodeBase64 , "UTF-8");
and than just
src="data:image/jpeg;base64,[the value of your base64DataString]"

Related

Image printing with zebra printer using zpl command

I am trying to print image on zebra printer(LP-2844-Z) using zpl language. In ZPL documentaion it says you have to convert image into ASCII HexaDecimal. Then by using GF command you can print image.
I tried below code to get image and convert it into hexa decimal
URL oracle = new URL(urlString);
URLConnection yc = oracle.openConnection();
BufferedImage bufferedImage = ImageIO.read(yc.getInputStream());
int rowsData = bufferedImage.getWidth()/8;
System.out.println(rowsData);
byte[] pixel = ((DataBufferByte)bufferedImage.getRaster().getDataBuffer()).getData();
System.out.println(pixel.length);
System.out.println(Hex.encodeHex(pixel, false));
And then I tried to print this data using zebra printer but it is not printing correct image. I tried another code to get image bytes and converted it into hexa decimal
URL oracle = new URL(urlString);
URLConnection yc = oracle.openConnection();
InputStream inputStream = yc.getInputStream();
byte[] imageData = IOUtils.toByteArray(inputStream);
System.out.println(Hex.encodeHex(pixel, false));
Still I am not able to print correct image. I follow following URL (http://labelary.com/viewer.html) and tried to see code when we upload image. What I found that after uploading image, the base64 generated by zebra viewer is totally different which I generated using above code. I go through several post on stackoverflow but still I am not able to solve out this problem.
I know where I am doing mistake but I don't know how to solve it. Actually I am not able to generate ASCII Hex Base64 code for given image. This is my thought.
Any help is appriciated.
Thanks,
Give this function a try:
private static String zplEncode(String graphicFileLocation) {
Path imagePath = Paths.get(URI.create("file://" + graphicFileLocation));
String returnResults = "";
try {
byte[] binaryData = Files.readAllBytes(imagePath);
for (byte b : binaryData)
{
String hexRep = String.format("{0:X}", b);
if (hexRep.length() == 1)
hexRep = "0" + hexRep;
returnResults += hexRep;
}
} catch (IOException ex) {
// Do something here
}
return returnResults;
}
I based it upon this answer from 2012.

Who is adding "\n" in Base64 encoded image when I write it in a file? Java

WHAT I'M DOING
I need to send via HTTPS request a JsonArray with some data and images in Base64 encoded strings. This works well if data is stored in memory.
Now, I need to avoid load all data in memory and I'm creating a temporally file in android device with all data that I need to send.
To create the file, I'm writting lots of JsonObjects inside him. Some of this JsonObjects have a field that represents the image. When I detect one, I get the image path and I encode it with Base64 as a String.
UPDATE:
First of all, I inicialize the file and I get the bufferedWriter
File f = new File(privateSincronizePath+File.separator+"upload_"+timefile+".json");
f.createNewFile();
FileWriter fw = new FileWriter(f.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
Here is the code that create the image when exists:
JSONObject jobInf = new JSONObject();
jobInf.put("xx", "INSERT");
jobInf.put("xx", c.getString(c.getColumnIndex("xx")));
jobInf.put("xx", ""+c.getInt(c.getColumnIndex("xx")));
jobInf.put("xx", c.getString(c.getColumnIndex("xx")));
JSONObject jsonObject = new JSONObject(docu.filtre(dades, docu.getXx()));
Iterator<?> keys = jsonObject.keys();
boolean updated = false;
while(keys.hasNext() && !updated){
String key = (String)keys.next();
if (key != null && key.equals("path") && key.length() > 0){
jsonObject.put(key, getBase64EncodeFromImage(jsonObject.getString(key)));
updated = true;
}
}
jobInf.put("object", jsonObject);
escriure(bw, ","+jobInf.toString());
Method escriure():
UPDATE: This method is called every time I complete the creation of the JsonObject. Only append JsonObject as String to the file.
private void escriure(BufferedWriter bw, String s) throws IOException {
uploadLength += s.length();
bw.append(s);
}
Finally, when file is created, I'm reading it and, using OutputStream, I'm sending the data as Post parameters to the server:
this.Https_url = new URL(url+"/sync.php?");
HttpsURLConnection con = (HttpsURLConnection) Https_url.openConnection();
con.setReadTimeout(60000);
con.setConnectTimeout(60000);
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setFixedLengthStreamingMode(uploadLength);
OutputStream os = con.getOutputStream();
InputStream inp = new FileInputStream(new File(privateSincronizePath+File.separator+"upload_"+timefile+".json"));
byte[] buffer = new byte[1024];
int len;
while ((len = inp.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
inp.close();
os.close();
// Establim la connexió:
con.connect();
WHAT IS THE PROBLEM
The problem is simple. When i open the image in the server, the file is corrupted and doesn't show the image.
WHAT I NOTICED
If I capture the image Base64 string encoded, before write in the file, and uploads it in the server, the image is Ok! Then, after write in the file, the image seems to be corrupted.
After investigate, I noticed that the Base64 encoded string after be written in the file, it have a lot of "\n" every x characters.
If I delete all of this "\n" or breaklines, the image can be opened by the server correctly.
THE QUESTION
Who is putting this breaklines? How can I write the Base64 encoded as String "as is" ?
Thanks all for your help in advance!
THE ANSWER
As Schoenobates answer, the solution was use the flag NO_WRAP.
To add more information, we put in the server side this function to read the encoded Base64 string with flag URL_SAFE
The function, obtained in on coment of TOM in php.net is:
<?php
function base64url_decode($base64url)
{
$base64 = strtr($base64url, '-_', '+/');
$plainText = base64_decode($base64);
return ($plainText);
}
?>
Thanks to StackOverflow, Axel and Schoenobates for your time!
That'll be the Android Base64 class - you need to set the flags to remove the newlines:
byte[] image = ...;
Base64.encodeToString(image, Base64.NO_WRAP | Base64.URL_SAFE);

is it possible to convert .swf file to base64 format in java

I am trying to load a .swf file in my page, i would like to make this load faster by converting it to Base64, rather providing a src. This is working great with image formats by using the below code
Java code
BufferedImage buffImg = ImageIO.read(new File(imagePath));
ImageIO.write(buffImg, imgExtension, bos);
byte[] imageBytes = bos.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(imageBytes);
but this is not working for swf file. is there any possible way to achieve this.
Html
<object width="10" height="10" data="data:application/x-shockwave-flash;base64, RldTCSEAAABIAZAAZAAADAEARBEIAAAAQwIAAP9AAAAA"></object>
thanks in advance.
Trying to get the file in base64 will not speed up the file transfer, it's just the opposite as it will convert the file which is stored in bytes (base256 if it can be said that way) to base64 (64 printable characters), so the final amount of data you will be transfering is more.
The only "win" is that you might be able to load it as part of the page instead of the browser making another call for the swf file, which should be no issue on http 1.1.
Unless you have some other good reason to do this, I would not suggest this kind of practice.
If you have your swf file(s) in a database as a blob, you could just make a servlet which sets the proper contenttype and write the whole file with the ServletOutputStream, without any tags. In your html code, you would have to reference to the servlet instead of a fixed file.
If you still want to convert the file to base64, you shouldn't use some image API, but get the file in a standard way for binary files, here's a sample that should do the job:
http://www.javapractices.com/topic/TopicAction.do?Id=245
You can still do the encoding as you did it once you have a byte array:
File file = new File(imagePath);
log("File size: " + file.length());
byte[] result = null;
try {
InputStream input = new BufferedInputStream(new FileInputStream(file));
result = readAndClose(input);
}
catch (FileNotFoundException ex){
log(ex);
}
BASE64Encoder encoder = new BASE64Encoder();
imageString = encoder.encode(result);
And the readAndClose method:
byte[] readAndClose(InputStream aInput){
byte[] bucket = new byte[32*1024];
ByteArrayOutputStream result = null;
try {
try {
result = new ByteArrayOutputStream(bucket.length);
int bytesRead = 0;
while(bytesRead != -1){
bytesRead = aInput.read(bucket);
if(bytesRead > 0){
result.write(bucket, 0, bytesRead);
}
}
}
finally {
aInput.close();
}
}
catch (IOException ex){
log(ex);
}
return result.toByteArray();
}
This should do the trick, maybe some fine tunings to adapt the code to your specific situation, optimize it and better error handling...

Display image with base64 String in html?

here is my java code that construct the base64 String from image. Then place the base64 String html, to view
the constructed image, but image is not constructed somehow
public void getBase64String() throws FileNotFoundException {
FileInputStream itStrm = new FileInputStream(
"E:\\image\\56255254-flower.jpg");//image is lying at http://danny.oz.au/travel/mongolia/p/56255254-flower.jpg
String str = itStrm.toString();
byte[] b3 = str.getBytes();
String base64String = new sun.misc.BASE64Encoder().encode(b3);
//output of base64String is amF2YS5pby5GaWxlSW5wdXRTdHJlYW1AMTdlMDYwMA==
}
Now in html page i placed the output of base64String in img tag to view the image.But image does not shows up
(instead it display the cross image icon). I am not getting image is not displayed from base64 String below?
<HTML>
<BODY>
<img src="data:image/jpeg;base64,amF2YS5pby5GaWxlSW5wdXRTdHJlYW1AMTdlMDYwMA=="/>
</BODY>
</HTML>
EDIT:- Thanks Folks, i used byte[] bytes = IOUtils.toByteArray(is);. It worked for me!!
This: String str = itStrm.toString() is not the image but the toString() representation of the FileInputStream instance.
You'll have to read the bytes from the stream and store them in a byte array. And, for performance reasons, buffer the stream:
BufferedInputStream itStrm = new BufferedInputStream(FileInputStream(
"E:\\image\\56255254-flower.jpg"));
Further reading (Spoiler: solution inside)
Convert InputStream to byte array in Java
You would need to use the read() method of the FileInputStream instance instead of the toString() to get the content of the image. Then you are able to encode it and should work as you expected.
Something like:
int c;
StringBuffer result = new StringBuffer("");
while((c = fileInputStream.read()) != -1)
{
result .append((char)c);
}

Strange byte[] behavior reading from a URL

In the end, my ultimate goals are:
Read from a URL (what this question is about)
Save the retrieved [PDF] content to a BLOB field in a DB (already have that nailed down)
Read from the BLOB field and attach that content to an email
All without going to a filesystem
The goal with the following method is to get a byte[] that can be used downstream as an email attachment (to avoid writing to disk):
public byte[] retrievePDF() {
HttpClient httpClient = new HttpClient();
GetMethod httpGet = new GetMethod("http://website/document.pdf");
httpClient.executeMethod(httpGet);
InputStream is = httpGet.getResponseBodyAsStream();
byte[] byteArray = new byte[(int) httpGet.getResponseContentLength()];
is.read(byteArray, 0, byteArray.length);
return byteArray;
}
For a particular PDF, the getResponseContentLength() method returns 101,689 as the length. The strange part is that if I set a break-point and interrogate the byteArray variable, it has 101,689 byte elements, however, after byte #3744 the remaining bytes of the array are all zeroes (0). The resulting PDF is then not readable by a PDF-reader client, like Adobe Reader.
Why would that happen?
Retrieving this same PDF via browser and saving to disk, or using a method like the following (which I patterned after an answer to this StackOverflow post), results in a readable PDF:
public void retrievePDF() {
FileOutputStream fos = null;
URL url;
ReadableByteChannel rbc = null;
url = new URL("http://website/document.pdf");
DataSource urlDataSource = new URLDataSource(url);
/* Open a connection, then set appropriate time-out values */
URLConnection conn = url.openConnection();
conn.setConnectTimeout(120000);
conn.setReadTimeout(120000);
rbc = Channels.newChannel(conn.getInputStream());
String filePath = "C:\\temp\\";
String fileName = "testing1234.pdf";
String tempFileName = filePath + fileName;
fos = new FileOutputStream(tempFileName);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
fos.flush();
/* Clean-up everything */
fos.close();
rbc.close();
}
For both approaches, the size of the resulting PDF is 101,689-bytes when doing a Right-click > Properties... in Windows.
Why would the byte array essentially "stop" part-way through?
InputStream.read reads up to byteArray.length bytes but might not read exactly that much. It returns how many bytes it read. You should call it repeatedly to fully read the data, like this:
int bytesRead = 0;
while (true) {
int n = is.read(byteArray, bytesRead, byteArray.length);
if (n == -1) break;
bytesRead += n;
}
Check the return value of InputStream.read. It's not going to read all at one go. You have to write a loop. Or, better yet, use Apache Commons IO to copy the stream.
101689 = 2^16 + 36153 so it would look like, that there is a 16 bit limitation on buffer size.
The difference between 36153 and 3744 maybe stems from the header part having been read in an extra small 1K buffer or so, and already containing some bytes.

Categories

Resources