It's possible to embed font to Flying Saucer image generation? - java

I'm trying to generate a image from a URL.
It works perfectly in my Windows local machine, but it does not work on my linux server.
I suspect that linux does not have the font, so it is generating the wrong image.
image windows local version
image linux server version
this is my code:
import org.w3c.dom.Document;
import org.xhtmlrenderer.simple.Graphics2DRenderer;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
class MyClass{
plublic ByteArrayInputStream getImageFromURL(String endereco){
Document doc= Jsoup.connect(endereco).get();
Graphics2DRenderer g2r = new Graphics2DRenderer();
g2r.setDocument(doc, endereco);
Dimension dim = new Dimension(1200, 1000);
// do layout with temp buffer
BufferedImage buff = new BufferedImage((int) dim.getWidth(), (int) dim.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) buff.getGraphics();
g2r.layout(g, dim);
g.dispose();
// get size
Rectangle rect = g2r.getMinimumSize();
// render into real buffer
buff = new BufferedImage((int) rect.getWidth(), (int) rect.getHeight(), BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) buff.getGraphics();
g2r.render(g);
g.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(buff, "png", os);
} catch (IOException e) {
e.printStackTrace();
}
return new ByteArrayInputStream(os.toByteArray());
}
}
the ByteArrayInputStream returned is the result image.
openhtmltopdf core image transformation (https://github.com/danfickle/openhtmltopdf) (flying saucer based)

Related

How to convert multi-line text to image using Java [closed]

I want to ask one question regarding my code which is how do I convert a multiple-line text into a single image using BufferReader. I am able to get the image of the text but all the lines of the text are coming as one single string in one line.
Enclosing my code. Please review my code and suggest me as soon as possible:
package mypack;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.imageio.ImageIO;
public class ImageDemo {
public static void main(String[] args) throws IOException {
// reading the String object from a file to be converted to image
/*File file = new File("D:/Vivek.txt");
StringBuilder sb=new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(file));
while(true)
{
String text=reader.readLine();
System.out.println(text);
if(text==null)
break;
sb.append(text).append(' ');
sb.append("\n");
}
String text1=sb.toString();
reader.close();*/
String text=new String(Files.readAllBytes(Paths.get("D:/Vivek.txt")), StandardCharsets.UTF_8);
System.out.println(text);
// Image file name
String fileName = "Image";
// create a File Object
File newFile = new File("D:/Vivek.jpg");
// create the font you wish to use
Font font = new Font("Tahoma", Font.PLAIN, 20);
// create the FontRenderContext object which helps us to measure the
// text
FontRenderContext frc = new FontRenderContext(null, true, true);
// get the height and width of the text
Rectangle2D bounds = font.getStringBounds(text, frc);
int w = (int) bounds.getWidth();
int h = (int) bounds.getHeight();
// create a BufferedImage object
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
// calling createGraphics() to get the Graphics2D
Graphics2D g = image.createGraphics();
// set color and other parameters
g.setColor(Color.white);
g.fillRect(0, 0, w, h);
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString(text, (float) bounds.getX(), (float) -bounds.getY());
// releasing resources
g.dispose();
RenderedImage rImage = (RenderedImage) image;
// creating the file
ImageIO.write(rImage, "jpeg", newFile);
//merging the two buffered images to get a new image with text along with logo.
//load the source images
BufferedImage img1=ImageIO.read(new File("D:/Vivek.jpg"));
BufferedImage img2=ImageIO.read(new File("D:/logo.jpg"));
BufferedImage joined=joinBufferedImage(img1, img2);
ImageIO.write(joined, "png", new File("D:/Joined.png"));
System.out.println("Success");
}
public static BufferedImage joinBufferedImage(BufferedImage img1,BufferedImage img2) {
//do some calculate first
int offset = 500;
int wid = img1.getWidth()+img2.getWidth()+offset;
int height = Math.max(img1.getHeight(),img2.getHeight())+offset;
//create a new buffer and draw two image into the new image
BufferedImage newImage = new BufferedImage(wid,height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = newImage.createGraphics();
Color oldColor = g2.getColor();
//fill background
g2.setPaint(Color.WHITE);
g2.fillRect(0, 0, wid, height);
//draw image
g2.setColor(oldColor);
g2.drawImage(img2, null, 0, 0);
g2.drawImage(img1, null, 170, 150);
g2.dispose();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
return newImage;
}
}
Hi here I am writing multiple lines on JPanel. And you can write code which create Image from JPanel.
package Stakeoverflow.swingFrame;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class MultiLineTextToImage{
public static void main(String[] args) {
String text = "Hello";
/*
Because font metrics is based on a graphics context, we need to create
a small, temporary image so we can ascertain the width and height
of the final image
*/
int width = 1000;
int height = 1000;
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
Font font = new Font("Arial", Font.PLAIN, 48);
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
g2d.dispose();
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
g2d = img.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2d.setFont(font);
//fm = g2d.getFontMetrics();
g2d.setColor(Color.BLACK);
File file = new File("C:\\Read.text");
BufferedReader br=null;
int nextLinePosition=100;
int fontSize = 48;
try {
br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
g2d.drawString(line, 0, nextLinePosition);
nextLinePosition = nextLinePosition + fontSize;
}
br.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Testing.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Testing.class.getName()).log(Level.SEVERE, null, ex);
}
g2d.dispose();
try {
ImageIO.write(img, "png", new File("Text.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

How To Convert Image .dcm to Graycale in Java

please i need help
I am trying to convert image .dcm to grayscale in java but i couldn't.
i wan't to know how to read image.dcm in java and convert it to grayscale.
note :: this code is already run for image .jpg,.png
package otsuthresholding;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
public class OtsuThresholding {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME );
File input = new File("p.dcm");
BufferedImage image = ImageIO.read(input);
byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);
mat.put(0, 0, data);
Mat mat1 = new Mat(image.getHeight(),image.getWidth(),CvType.CV_8UC1);
Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2GRAY);
byte[] data1 = new byte[mat1.rows() * mat1.cols() * (int)(mat1.elemSize())];
mat1.get(0, 0, data1);
BufferedImage image1 = new BufferedImage(mat1.cols(),mat1.rows(), BufferedImage.TYPE_BYTE_GRAY);
image1.getRaster().setDataElements(0, 0, mat1.cols(), mat1.rows(), data1);
File ouptut = new File("grayscale.dcm");
ImageIO.write(image1, "dcm", ouptut);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Does Apache POI API support PPTX2PNG conversion (in java programs) for pptx generated by LibreOffice Impress?

I am trying to convert the pptx to png images using apache-poi in java but it doesn't work with pptx generated by LibreOffice Impress (works fine with others ) and there is no exception thrown.
The resulting images I get are just the background with out the text content of the pptx.
Please see the links for the results.
The resulting image
Screen shot of Actual pptx slide
This is the basic code I got :
package com.preview;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
public class PptxToPng {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileInputStream is = new FileInputStream("~/Downloads/pptx/SamplePPTX.pptx");
XMLSlideShow ppt = new XMLSlideShow(is);
is.close();
double zoom = 2;
AffineTransform at = new AffineTransform();
at.setToScale(zoom, zoom);
Dimension pgsize = ppt.getPageSize();
List<XSLFSlide> slide = ppt.getSlides();
BufferedImage img = new BufferedImage((int)Math.ceil(pgsize.width*zoom),
(int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setTransform(at);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// Draw first page in the PPTX. First page starts at 0 position
slide.get(0).draw(graphics);
FileOutputStream out = new FileOutputStream("~/Downloads/pptx/converted.png");
javax.imageio.ImageIO.write(img, "png", out);
out.close();
ppt.close();
System.out.println("DONE");
}
}
poi-ooxml-3.15.jar comes with a tool called PPTX2PNG. It can be found in the package org.apache.poi.xslf.util
Execute it eg with parameters -scale 1 -format jpg pptx-file.pptx and it should write an image file to the same directory as the origin pptx file.
BTW: despite the name, it can write to png, jpg and gif formats.

Unicode characters not converting from pptx to png

I have written a program to convert PPTX to PNG. All the conversion happens fine only issue is where ever there is UNICODE character in PPTX file - it converts that to a junk character. Here is the code. I tried to add fonts but that did not help. This is what PPTX contains - "/ˌinəˈvāSHən/". It converts letters i, n, v, a, S, H, n fine but not others.
FileInputStream is = new FileInputStream(strTempPath);
XMLSlideShow pptx = new XMLSlideShow(is);
is.close();
double zoom = 2; // magnify it by 2
AffineTransform at = new AffineTransform();
at.setToScale(zoom, zoom);
Dimension pgsize = pptx.getPageSize();
XSLFSlide[] slide = pptx.getSlides();
}
// BufferedImage img = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_INT_RGB);
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
//graphics.setTransform(at);
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
slide[iPageNo].draw(graphics);
// FileOutputStream output = new ByteArrayOutputStream("C:/Temp/aspose/word/slide-" + (10 + 1) + ".png");
output = new ByteArrayOutputStream();
javax.imageio.ImageIO.write(img, "png", output);
This is how I am trying to add fonts but still did not convert.
Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("/usr/share/fonts/GEInspRg.ttf")).deriveFont(12f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
//register the font
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("/usr/share/fonts/GEInspRg.ttf")));
graphics.setFont(customFont);
Here is the code I have: also given in the original question: And my test PPTX contains this word - /ˌinəˈvāSHən/ in addition to other English letter words.
package foo;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
public class PPTXToPNG {
public static void main(String[] args) throws Exception {
FileInputStream is = new FileInputStream("C:/Temp/PPTXToImage/unicode_test.pptx");
XMLSlideShow ppt = new XMLSlideShow(is);
is.close();
double zoom = 2;
AffineTransform at = new AffineTransform();
at.setToScale(zoom, zoom);
Dimension pgsize = ppt.getPageSize();
XSLFSlide[] slide = ppt.getSlides();
BufferedImage img = new BufferedImage((int)Math.ceil(pgsize.width*zoom),
(int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setTransform(at);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// Draw first page in the PPTX. First page starts at 0 position
slide[0].draw(graphics);
FileOutputStream out = new FileOutputStream("C:/Temp/PPTXToImage/ConvertedSlide.png");
javax.imageio.ImageIO.write(img, "png", out);
out.close();
System.out.println("DONE");
}
}
As Jongware pointed out above, the characters are not available in the "GE Inspira" font, as you can see in the example programm below - so you'll need some /ˌinəˈvāSHən/ (innovation) to come around that ;)
There are several approaches I can think off:
I'm not sure if this graphics.setFont(customFont); for setting the in your code was just a test, but normally POI will use (and set) the font, which was specified in the document. So the easiest would be to replace the font in the original document with a font which supports phonetics (see the wikipedia unicode article for suitable fonts). Btw. if you try to use that font in Libre Office and insert these phonetics you'll also get "junk" chars.
you could use something like fontforge to add the missing chars to your preferred font from a different font (but of course it need to be used - see above). It would look a bit strange, but better than rectangles ...
you could check beforehand if certain chars in the text-runs are supported for the specified font and insert a new text-run element with an alternative font for the unsupported chars
I know that PDFs have some kind of font substitution going on, in case a font (or even a character???) can't be found, I haven't found a similar mechanism for java in a short search ... maybe there's also a solution in this way ...
(tested with POI 3.10-beta1)
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import org.apache.poi.xslf.usermodel.*;
public class UnicodePPT {
public static void main(String[] args) throws Exception {
// create a sample pptx
XMLSlideShow ss = new XMLSlideShow();
Dimension pgsize = ss.getPageSize();
XSLFSlide slide = ss.createSlide();
XSLFTextBox tb = slide.createTextBox();
tb.setShapeType(XSLFShapeType.HEART);
int shapeSize = 150;
tb.setAnchor(new Rectangle2D.Double(pgsize.getWidth()/2-shapeSize/2, pgsize.getHeight()/2-shapeSize/2, shapeSize, shapeSize));
tb.setLineWidth(2);
tb.setLineColor(Color.BLACK);
XSLFTextParagraph par = tb.addNewTextParagraph();
tb.setVerticalAlignment(VerticalAlignment.DISTRIBUTED);
par.setTextAlign(TextAlign.CENTER);
XSLFTextRun run = par.addNewTextRun();
run.setText("/\u02CCin\u0259\u02C8v\u0101SH\u0259n/");
run.setFontFamily("DejaVu Serif");
run.setFontSize(12);
par.addLineBreak();
run = par.addNewTextRun();
run.setText("/\u02CCin\u0259\u02C8v\u0101SH\u0259n/");
run.setFontFamily("GE Inspira");
run.setFontSize(12);
// set the font
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
InputStream is = new FileInputStream("src/main/resources/GEInspRg.TTF");
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
is.close();
ge.registerFont(font);
is = new FileInputStream("src/main/resources/DejaVuSerif.ttf");
font = Font.createFont(Font.TRUETYPE_FONT, is);
is.close();
ge.registerFont(font);
// render it
double zoom = 2; // magnify it by 2
AffineTransform at = new AffineTransform();
at.setToScale(zoom, zoom);
BufferedImage img = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setTransform(at);
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
slide.draw(graphics);
FileOutputStream fos = new FileOutputStream("unicodeppt.png");
javax.imageio.ImageIO.write(img, "png", fos);
fos.close();
}
}

Image transformation results in a red image?

I am trying to transform an image by flipping it horizontally and resizing it. The problem is that when the transformation is done the picture's colors are all weird, it has gotten this reddish tone. Is it possible to fix this somehow, I think I read somewhere that it might be some bug in the AWT library but I am not sure?
Here is the code:
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class LocalImageSizeFlip {
public static void main(String[] args) {
BufferedImage img = null;
try {
img = ImageIO.read(new File("C:\\picture.jpg"));
AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
tx.translate(0, -img.getHeight(null));
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
img = op.filter(img, null);
img = resize(img, 100, 75);
File newFile = new File("newPicture.jpg");
ImageIO.write(img, "JPEG", newFile);
} catch (IOException e) {
e.printStackTrace();
}
}
private static BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage resizedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
}
Having an image develop a tint usually means the image is being rendered using the wrong colorspace, Adobe RGB vs. sRGB being a perennial favorite. Try changing TYPE_INT_ARGB to TYPE_INT_RGB in your code.
You can also try the following type: BufferedImage.TYPE_3BYTE_BGR

Resources