Feemarker writing images to html - java

is there anyway to write image in freemarker instead of giving link as
<img src="${pathToPortalImage}
Note : cant we use otputstream or something in freemarker ?

You can embed the image as base64 directly inside the html img tag.
To convert an image to base 64 you can use Apache Commons (codec).
Here is a solution using Apache Commons IO + Codec (but you can do without if you want):
File img = new File("file.png");
byte[] imgBytes = IOUtils.toByteArray(new FileInputStream(img));
byte[] imgBytesAsBase64 = Base64.encodeBase64(imgBytes);
String imgDataAsBase64 = new String(imgBytesAsBase64);
String imgAsBase64 = "data:image/png;base64," + imgDataAsBase64;
Then pass the variable imgAsBase64 into the Freemarker context, and use it like this:
<img alt="My image" src="${imgAsBase64}" />

A great example above. But with JAVA 8 we can do something like this:
Path path = Paths.get("image.png");
byte[] data = Files.readAllBytes(path);
byte[] encoded = Base64.getEncoder().encode(data);
String imgDataAsBase64 = new String(encoded);
String imgAsBase64 = "data:image/png;base64," + imgDataAsBase64;

private String encodeImage(byte[] imageByteArray, String fileType) {
return "data:" + fileType + ";base64," + Base64.getEncoder().encodeToString(imageByteArray);
}
use output in below tag
<img src="[OUTPUT_OF_ABOVE_METHOD]">

Related

Image to byte array in Codename One

I need to convert an image into a byte array in my Codename One app.
It will be used to create a base64 representation of the image to be used in a BrowserComponent.
I tried this:
byte[] bytes=new byte[10];
String base64IconString="data:image/png;base64,";
try(InputStream is = getClass().getResourceAsStream("/icon.png");) {
bytes=new byte[is.available()];
// the instruction above is wrong. it will fail
// use Util.readInputStream(InputStream) in Codename One instead
// see comments
Util.readAll(is, bytes);
base64IconString+=Base64.encode(bytes);
} catch(IOException err) {
Log.e(err);
}
I put the result into this:
browserComponent.setPage("<HTML><BODY>" + "<img src='"+base64IconString+"' />" + "</BODY></HTML>");
It works, but I need to create the base64 string from a Image that has no path or file name because it is from a special class MyImageFromSVGSubset.
This tool is used to generate that class: https://www.codenameone.com/blog/flamingo-svg-transcoder.html
Note: the Image class in CodenameOne has also the int[] getRGB() method.
How to achieve my goal?
You can use ImageIO which is designed exactly for that: converting an Image to bytes. However, there's a slightly simpler hack. EncodedImage supports this out of the box so:
EncodedImage em = EncodedImage.createFromImage(otherImage, jpegOrPNG);
byte[] data = em.getImageData();
Also see BrowserComponent.createDataURI(byte[], mime).

How to properly open a png file

I am trying to attach a png file. Currently when I sent the email, the attachment is 2x bigger than the file should be and an invalid png file. Here is the code I currently have:
import com.sendgrid.*;
Attachments attachments = new Attachments();
String filePath = "/Users/david/Desktop/screenshot5.png";
String data = "";
try {
data = new String(Files.readAllBytes(Paths.get(filePath)));
} catch (IOException e) {
}
byte[] encoded = Base64.encodeBase64(data.getBytes());
String encodedString = new String(encoded);
attachments.setContent(encodedString);
Perhaps I am encoding the data incorrectly? What would be the correct way to 'get' the data to attach it?
With respect, this is why Python presents a problem to modern developers. It abstracts away important concepts that you can't fully understand in interpreted languages.
First, and this is a relatively basic concept, but you can't convert arbitrary byte sequences to a string and hope it works out. The following line is your first problem:
data = new String(Files.readAllBytes(Paths.get(filePath)));
EDIT: It looks like the library you are using expects the file to be base64 encoded. I have no idea why. Try changing your code to this:
Attachments attachments = new Attachments();
String filePath = "/Users/david/Desktop/screenshot5.png";
try {
byte[] encoded = Base64.encodeBase64(Files.readAllBytes(Paths.get(filePath)));
String encodedString = new String(encoded);
attachments.setContent(encodedString);
} catch (IOException e) {
}
The only issue you were having is that you were trying to represent arbitrary bytes as a string.
Take a look at the Builder class in the repository here. Example:
FileInputStream fileContent = new FileInputStream(filePath);
Attachments.Builder builder = new Attachments.Builder(fileName, fileContent);
mail.addAttachments(builder.build());

convert image to base64 with java

I need to convert a image object to a base64 object so I can load it into the tag on my client side.
However I can't seem to figure out how to pull this off. Is there anyone who has a piece of code for this that I could use easily?
This is what I use to turn the external image link into a image object
Image image = null;
URL url = new URL(request.getParameter("hdn_path"));
image = ImageIO.read(url);
not sure if I'm going about this the correct way.
Using Apache IOUtils and Base64:
byte[] imageBytes = IOUtils.toByteArray(new URL("...")));
String base64 = Base64.getEncoder().encodeToString(imageBytes);
write using ImageIO.write().
ByteArrayOutputStream wraps the byte array so it can be used as an output stream.
convert the byte array to a a base64 string using DatatypeConverter, in core Java since 6, no extra libraries required
Example
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(image, "png", output);
DatatypeConverter.printBase64Binary(output.toByteArray());
Accepted answer reads the file from URL, if any one looking for image to Base64 encoding by reading the image from file system, below snippet can be used.
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Base64;
import org.apache.commons.io.IOUtils;
public String img2Text(){
String base64="";
try{
InputStream iSteamReader = new FileInputStream("featured-700x467.png");
byte[] imageBytes = IOUtils.toByteArray(iSteamReader);
base64 = Base64.getEncoder().encodeToString(imageBytes);
System.out.println(base64);
}catch(Exception e){
e.printStackTrace();
}
return "data:image/png;base64,"+base64;
}
Returned base64 text can be used in HTML pages like below example
<!DOCTYPE html>
<html>
<body>
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACoAAAAqCAYAAADFw8lbAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAfDSURBVFhHrZihb2NHEMatKpUCAgIMQgMOFIZUKg3oH9F/oaCwqo4GFAREVRUdMDWwTgcCopOB6VNlEFXRySDgUUtxKoMAA1+0N7/Z/db7Xl5in64rjd++3X0z3347M7vr3tFxL7wmlLIewjI9N+1lf3c9ftNu/xrZCahKu+8xYV6tHvNY6i6P89zfVehr63tNtgKVqOh9sVjn9rt6Fh7uFw6O+v39nb8j9Tyi5anx0gHTqm+TnYCqLB8jGKSezxzUp093Lv/8Ow3T6dilqqb5/XY2DpPpxL+f3S1cx+O6zquwq+y89CjGAGwBAnAA+vhxGkajSRi8G4fhYBAGw2G4fHdp76MwHI28j/GT6kO4ub0Nd3frMK+Xzjb6umx2yVagAFyuo+Kb6W1m0IEMqnB+NgwHe8eh1+uFvb4ptGdbzs/OHfzV1VWYjG+d2ewuyae7bJfyIlApYNZSWk1m4f37q/D27a/hKIE6trHz+WH4HH4Mi6Wtw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wNYU3rhC7E8UDjURuIvAAAAAElFTkSuQmCC
" alt="Smiley face" width="42" height="42">
</body>
</html>

Is it possible to encode a file as a Data URI in Java?

I have the need to encode a file as a data URI in Java, is it possible for me to retrieve this in the following format?
data:application/octet-stream;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA==
I've been looking for something like it, but had no luck so far.
I don't think there is a utility function specifically for creating it, but it should be as simple as:
import org.apache.commons.codec.binary.Base64;
byte[] toEncode = { 0xaa, 0xbb, 0xcc };
Base64 base64NoLineWrap = new Base64(0);
String encodedData = base64NoLineWrap.encodeBase64String(toEncode);
String dataUri = "data:application/octet-stream;base64," + encoded;

Java - Image encoding in XML

I thought I would find a solution to this problem relatively easily, but here I am calling upon the help from ye gods to pull me out of this conundrum.
So, I've got an image and I want to store it in an XML document using Java. I have previously achieved this in VisualBasic by saving the image to a stream, converting the stream to an array, and then VB's xml class was able to encode the array as a base64 string. But, after a couple of hours of scouring the net for an equivalent solution in Java, I've come back empty handed. The only success I have had has been by:
import it.sauronsoftware.base64.*;
import java.awt.image.BufferedImage;
import org.w3c.dom.*;
...
BufferedImage img;
Element node;
...
java.io.ByteArrayOutputStream os = new java.io.ByteArrayOutputStream();
ImageIO.write(img, "png", os);
byte[] array = Base64.encode(os.toByteArray());
String ss = arrayToString(array, ",");
node.setTextContent(ss);
...
private static String arrayToString(byte[] a, String separator) {
StringBuffer result = new StringBuffer();
if (a.length > 0) {
result.append(a[0]);
for (int i=1; i<a.length; i++) {
result.append(separator);
result.append(a[i]);
}
}
return result.toString();
}
Which is okay I guess, but reversing the process to get it back to an image when I load the XML file has proved impossible. If anyone has a better way to encode/decode an image in an XML file, please step forward, even if it's just a link to another thread that would be fine.
Cheers in advance,
Hoopla.
I've done something similar (encoding and decoding in Base64) and it worked like a charm. Here's what I think you should do, using the class Base64 from the Apache Commons project:
// ENCODING
BufferedImage img = ImageIO.read(new File("image.png"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "png", baos);
baos.flush();
String encodedImage = Base64.encodeToString(baos.toByteArray());
baos.close(); // should be inside a finally block
node.setTextContent(encodedImage); // store it inside node
// DECODING
String encodedImage = node.getTextContent();
byte[] bytes = Base64.decode(encodedImage);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
Hope it helps.
Apache Commons has a Base64 class that should be helpful to you:
From there, you can just write out the bytes (they are already in a readable format)
After you get your byte array
byte[] array = Base64.encode(os.toByteArray());
use an encoded String :
String encodedImg = new String( array, "utf-8");
Then you can do fun things in your xml like
<binImg string-encoding="utf-8" bin-encoding="base64" img-type="png"><![CDATA[ encodedIImg here ]]></binImg>
With Java 6, you can use DatatypeConverter to convert a byte array to a Base64 string:
byte[] imageData = ...
String base64String = DatatypeConverter.printBase64Binary(imageData);
And to convert it back:
String base64String = ...
byte[] imageData = DatatypeConverter.parseBase64Binary(base64String);
Your arrayToString() method is rather bizarre (what's the point of that separator?). Why not simply say
String s = new String(array, "US-ASCII");
The reverse operation is
byte[] array = s.getBytes("US-ASCII");
Use the ASCII encoding, which should be sufficient when dealing with Base64 encoded data. Also, I'd prefer a Base64 encoder from a reputable source like Apache Commons.
You don't need to invent your own XML data type for this. XML schema defines standard binary data types, such as base64Binary, which is exactly what you are trying to do.
Once you use the standard types, it can be converted into binary automatically by some parsers (like XMLBeans). If your parser doesn't handle it, you can find classes for base64Binary in many places since the datatype is widely used in SOAP, XMLSec etc.
most easy implementation I was able to made is as below, And this is from Server to Server XML transfer containing binary data Base64 is from the Apache Codec library:
- Reading binary data from DB and create XML
Blob blobData = oRs.getBlob("ClassByteCode");
byte[] bData = blobData.getBytes(1, (int)blobData.length());
bData = Base64.encodeBase64(bData);
String strClassByteCode = new String(bData,"US-ASCII");
on requesting server read the tag and save it in DB
byte[] bData = strClassByteCode.getBytes("US-ASCII");
bData = Base64.decodeBase64(bData);
oPrStmt.setBytes( ++nParam, bData );
easy as it can be..
I'm still working on implementing the streaming of the XML as it is generated from the first server where the XML is created and stream it to the response object, this is to take care when the XML with binary data is too large.
Vishesh Sahu
The basic problem is that you cannot have an arbitrary bytestream in an XML document, so you need to encode it somehow. A frequent encoding scheme is BASE64, but any will do as long as the recipient knows about it.
I know that the question was aking how to encode an image via XML, but it is also possible to just stream the bytes via an HTTP GET request instead of using XML and encoding an image. Note that input is a FileInputStream.
Server Code:
File f = new File(uri_string);
FileInputStream input = new FileInputStream(f);
OutputStream output = exchange.getResponseBody();
int c = 0;
while ((c = input.read()) != -1) {
output.write(c); //writes each byte to the exchange.getResponseBody();
}
result = new DownloadFileResult(int_list);
if (input != null) {input.close();}
if (output != null){ output.close();}
Client Code:
InputStream input = connection.getInputStream();
List<Integer> l = new ArrayList<>();
int b = 0;
while((b = input.read()) != -1){
l.add(b);//you can do what you wish with this list of ints ie- write them to a file. see code below.
}
Here is how you would write the Integer list to a file:
FileOutputStream out = new FileOutputStream("path/to/file.png");
for(int i : result_bytes_list){
out.write(i);
}
out.close();
node.setTextContent( base64.encodeAsString( fileBytes ) )
using org.apache.commons.codec.binary.Base64

Categories