convert html to image in byte array java - java

How can i easily convert html to image and then to byte array without create it
thanks

If you do not have any complex html you can render it using a normal JLabel. The code below will produce this image:
<html>
<h1>:)</h1>
Hello World!<br>
<img src="http://img0.gmodules.com/ig/images/igoogle_logo_sm.png">
</html>
public static void main(String... args) throws IOException {
String html = "<html>" +
"<h1>:)</h1>" +
"Hello World!<br>" +
"<img src=\"http://img0.gmodules.com/ig/images/igoogle_logo_sm.png\">" +
"</html>";
JLabel label = new JLabel(html);
label.setSize(200, 120);
BufferedImage image = new BufferedImage(
label.getWidth(), label.getHeight(),
BufferedImage.TYPE_INT_ARGB);
{
// paint the html to an image
Graphics g = image.getGraphics();
g.setColor(Color.BLACK);
label.paint(g);
g.dispose();
}
// get the byte array of the image (as jpeg)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
byte[] bytes = baos.toByteArray();
....
}
If you would like to just write it to a file:
ImageIO.write(image, "png", new File("test.png"));

I think you can use the library
html2image-0.9.jar
you can download this library at this page: http://code.google.com/p/java-html2image/

What about using an in memory ByteArrayStream instead of a FileOutputStream in the code above? That would be a byte array, at least ...

This is nontrivial because rendering a HTML page can be quite complex: you have text, images, CSS, possibly even JavaScript to evaluate.
I don't know the answer, but I do have something that might help you: code for iText (a PDF writing library) to convert a HTML page to a PDF file.
public static final void convert(final File xhtmlFile, final File pdfFile) throws IOException, DocumentException
{
final String xhtmlUrl = xhtmlFile.toURI().toURL().toString();
final OutputStream reportPdfStream = new FileOutputStream(pdfFile);
final ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(xhtmlUrl);
renderer.layout();
renderer.createPDF(reportPdfStream);
reportPdfStream.close();
}

Related

Using flying saucer convert html to Image

Using flying saucer, i successfully convert html to image using below code
//doc - html source code as org.w3c.dom.Document
Java2DRenderer renderer = new Java2DRenderer(doc, width, height);
BufferedImage img = renderer.getImage();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", os);
But i have problems in the above code like it does not render the font properly in the html.
Also if the chinese ,Japanese or other than Ascii characters given, the image has not been rendered with proper content(characters are boxed like below).
But actual html content is
<div ><ul><li><dl><dt>イベントについて<br></dt><dd><ul><li>サポーター&フレンズ<br></li></ul></dd></dl><dl><dt>イベント・セミナー一覧<br></dt></dl></li></ul><div><br></div></div>
Also in my case, any language will come, but all encoded using unicode. How to solve this.
Please help.
String html = "<div ><ul><li><dl><dt>イベントについて<br></dt><dd><ul><li>サポーター&フレンズ<br></li></ul></dd></dl><dl><dt>イベント・セミナー一覧<br></dt></dl></li></ul><div><br></div></div>"
//Read it using Utf-8 - Based on encoding, change the encoding name if you know it
InputStream htmlStream = new ByteArrayInputStream(html.getBytes("UTF-8"));
Tidy tidy = new Tidy();
org.w3c.dom.Document doc = tidy.parseDOM(new InputStreamReader(htmlStream,"UTF-8"), null);
Java2DRenderer renderer = new Java2DRenderer(doc, width, height);
BufferedImage img = renderer.getImage();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", os);
This solves my issue. On reading html stream using UTF-8 solves the issue.

Download image from SVG with Jersey

I have some SVG string from highcharts and I want to download it as an image (PNG).
The conversion is done using PNGTranscoder (Batik)
#POST
public Response getChartImage() throws Exception{
String svg = "<svg xmlns:xlink..."; // can be ignored
svg = svgDocumentConvertAndRevert(svg); // can be ignored
TranscoderInput input = new TranscoderInput(new StringReader(svg));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TranscoderOutput output = new TranscoderOutput(baos);
PNGTranscoder transcoder = new PNGTranscoder();
transcoder.transcode(input, output);
BufferedImage image = new BufferedImage(300, 500, 1);
ImageIO.write(image, "png", baos);
byte[] imageData = baos.toByteArray();
return Response.ok(imageData).build();
}
but what I'm getting is a bunch of text, something like
�PNG IHDR�#��E� cHRMz&��...
Tried with #Produces("image/*") but didn't work...
Can I not save it as an image (real file) and allow user to download it? Trying to avoid unnecessary effort..
Thanks!
You need to set the correct mime type for the response something like
response.setContentType("image/png");
where response is a ServletResponse object.
It was working, just that I was using Chrome's extension POSTman.

Write CMYK image in PDF

I need to add a CMYK Image (java.awt.BufferedImage) to a Pdf-Document with iText.
I'm trying to do it with:
com.lowagie.text.Image img = Image.getInstance(BufferedImage, bgColor);
This produces an RGB image in the resulting PDF. (and I suppose it's a bug, because it just ignores ColorModel). However I could use:
com.lowagie.text.Image img = Image.getInstance(byte[] rawData);
And it produces a correct CMYK-Image in PDF. But for the second case I need to convert java.awt.BufferedImage in ByteArray. I cannot do it with ImageIO.write(ByteArrayOutputStream). I also cannot do it with com.sun.image.codec.jpeg.JPEGImageEncoder because I must use OpenJDK.
Any ideas how can I achieve the correct behavior to write a CMYK image in PDF using iText?
So basically what you're asking is how to convert a BufferedImage to a byte[] to print to PDF?
BufferedImage img; // your image to be printed
String formatName; // name of the image format (see ImageIO docs)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( img, formatName, baos);
byte[] rawData = baos.toByteArray();
You should be able to use that for the CMYK-image as you had in your original post:
com.lowagie.text.Image img = Image.getInstance(byte[] rawData);

Convert iText Barcode Image from CCITT format to PNG

I'm using iText to create a PDF417 bar code like so:
private InputStream getBarcode() throws Exception {
BarcodePDF417 barcode = new BarcodePDF417();
barcode.setText("Sample bar code text");
Image image = barcode.getImage();
image.scalePercent(50, 50 * barcode.getYHeight());
return new ByteArrayInputStream(image.getRawData());
}
I need to convert the CCITT format returned by barcode.getImage() to either JPG, GIF, or PNG so I can include it in a document I'm creating in JasperReports.
How about something like this?
BarcodePDF417 barcode = new BarcodePDF417();
barcode.setText("Bla bla");
java.awt.Image img = barcode.createAwtImage(Color.BLACK, Color.WHITE);
BufferedImage outImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
outImage.getGraphics().drawImage(img, 0, 0, null);
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
ImageIO.write(outImage, "png", bytesOut);
bytesOut.flush();
byte[] pngImageData = bytesOut.toByteArray();
FileOutputStream fos = new FileOutputStream("C://barcode.png");
fos.write( pngImageData);
fos.flush();
fos.close();
The solution I came up with:
private Image getBarcode() throws Exception {
BarcodePDF417 barcode = new BarcodePDF417();
barcode.setText("Sample bar code text");
barcode.setAspectRatio(.25f);
return barcode.createAwtImage(Color.BLACK, Color.WHITE);
}
JasperReports supports the java.awt.Image type for images used in a report.

How can I save a JPEG from a URL to a file?

I am trying to save a JPEG image from a URL to a file with Java.
URL: http://150.214.222.100//axis-cgi/mjpg/video.cgi?resolution=640x480&compression=1&duration=1&timeout=&dummy=garb
I tried the following:
1)
Image image = fetchImage(urlNorthView);
saveImage2Disk(image);
public static Image fetchImage( URL u ) throws MalformedURLException, IOException {
Toolkit tk = Toolkit.getDefaultToolkit();
return tk.createImage(u );
}
private void saveImage2Disk(Image Image) throws IOException{
File outputFile = new File("urlNorthView"+Calendar.getInstance().getTimeInMillis()+".jpg");
BufferedImage bufferedImage = new BufferedImage(Image.getWidth(null),Image.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(Image, null, null);
ImageIO.write(bufferedImage, "jpg", outputFile);
}
=> Exception:"Width (-1) and height (-1) cannot be <= 0"
2)
inputStream2Disk((InputStream) urlNorthView.getContent());
private void inputStream2Disk(InputStream in) throws Exception{
File outputFile = new File("urlNorthView"+Calendar.getInstance().getTimeInMillis()+".jpg");
OutputStream out=new FileOutputStream(outputFile);
byte buf[]=new byte[1024];
int len;
while((len=in.read(buf))>0)
out.write(buf,0,len);
out.close();
in.close();
}
The file is somehow broken. When I open it with Kate, I can read:
--myboundary Content-Type: image/jpeg Content-Length: 38256 ....
There should not be any text in a binary file.
What could the problem be?
For some reason, the http response body when requesting that image contains a mime part (mime parts are useful for putting multiple files into a single response). In this response, there is only one mime part, so it is mostly useless.
There is code in the javax.mail package that you might be able to use to parse this properly if you want, but it's not a very good api, imho.
Alternatively, there are a bunch of ways you could hackishly fix this in code yourself. Since there's only one mime part, you can just throw away data from the beginning of your input stream until you see two newline characters in a row (bytes equal to 10). That should work since mime headers are supposed to be 7-bit ascii, iirc, so there's no character encoding to worry about.
Here is some sample code:
URLConnection conn = urlNorthView.openConnection();
InputStream in = conn.getInputStream();
String contentType = conn.getHeaderField("Content-Type");
if (!"image/jpeg".equals(contentType)) {
// hack: assuming it's mime if not a raw image
int one = in.read();
if (one == -1) {
// stop??
}
int two = in.read();
while (two != -1 && !(two == 10 && one == 10)) {
one = two;
two = in.read();
}
}
// if it was mime, we've stripped off the mime headers
// and should now get the image
inputStream2Disk(in);
Edit: crap, instead of two \n, you'll see two \r\n, or the bytes 0x0d, 0x0a, 0x0d, 0x0a. Throwing away data until you see this pattern is left as an exercise to the reader ;)
Try the following method for converting an Image to BufferedImage
private static BufferedImage getBufferedImage(Image img, int imageType) {
if (img instanceof BufferedImage) {
return (BufferedImage) img;
}
BufferedImage bi = new BufferedImage(img.getWidth(null), img
.getHeight(null), imageType);
Graphics2D g = (Graphics2D) bi.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(img, 0, 0, null);
g.dispose();
return bi;
}
(where imageType is one of the BufferedImage declared constants. Most likely TYPE_INT_RGB.
Otherwise your first approach is fine.
I'd recommend the first (high-level) approach over the second (low-level).

Categories

Resources