JavaFX Chart to Image to Base64 String use in PHP - java

i'am using JavaFX and illustrate a Chart with the LineChart concept in Javafx.
If i draw a chart, i export a screenshot of this with this code.
WritableImage image = lc.snapshot(new SnapshotParameters(), null);
File file = new File("Chart.png");
try {
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
}
catch (IOException e) {
//bla
}
This works perfect!
Now: is there a simple way to create this "WritableImage" image to a Base64 String? Furthermore i want to use it to reproduce this Base64-String to a PNG file in PHP.
Any Ideas?
THX

Your code need to continue with something like this:
//File file = new File("Chart.png"); -> this is already there
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read= 0;
while( (read = fis.read(buffer)) > -1){
baos.write(buffer, 0, read);
}
fis.close();
baos.close();
byte pgnBytes [] = baos.toByteArray();
Base64.Encoder base64_enc = Base64.getEncoder();
String base64_image = base64_enc.encodeToString(pgnBytes);
This can be optimized further to write the file directly into byte array, if you do not need the graphic stored into file:
WritableImage image = lc.snapshot(new SnapshotParameters(), null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", baos);
}
catch (IOException e) {
//bla
}
byte pgnBytes [] = baos.toByteArray();
Base64.Encoder base64_enc = Base64.getEncoder();
String base64_image = base64_enc.encodeToString(pgnBytes);
}
In both cases image is stored in memory, which can cause OutOfMemory Error, if the image is too large etc.

SwingFXUtils.fromFXImage() returns a BufferedImage which can be easily converted to a Base64-String using BASE64.Encoder introduced in Java 8.
A complete working example :
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
VBox box = new VBox();
box.setStyle("-fx-background-color:RED;");
Scene scene = new Scene(box, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
createEncodedString(box);
}
private void createEncodedString(Node node) {
WritableImage image = node.snapshot(new SnapshotParameters(), null);
String base64String = encodeImageToString(SwingFXUtils.fromFXImage(image, null), "png");
System.out.println("Base64 String : " + base64String);
}
private String encodeImageToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
imageString = Base64.getEncoder().encodeToString(imageBytes);
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return imageString;
}
}

Related

With iText Reading an image signature stream/object..is black background and white foreground, how to reverse

I am trying to read image objects from a PDF document. The image comes out as black background and white text. How can I reverse that. the image in the pdf, is white foreground and black background.
Here is the code, main piece for loading the image component
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PRStream;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfImageObject;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
public class MyImageRenderListener implements RenderListener {
/**
* The new document to which we've added a border rectangle.
*/
protected String path = "";
/**
* Creates a RenderListener that will look for images.
*/
public MyImageRenderListener(String path) {
this.path = path;
}
/**
* #see com.itextpdf.text.pdf.parser.RenderListener#beginTextBlock()
*/
public void beginTextBlock() {
}
/**
* #see com.itextpdf.text.pdf.parser.RenderListener#endTextBlock()
*/
public void endTextBlock() {
}
/**
* #see com.itextpdf.text.pdf.parser.RenderListener#renderImage(
*com.itextpdf.text.pdf.parser.ImageRenderInfo)
*/
public void renderImage(final ImageRenderInfo renderInfo) {
try {
String filename;
FileOutputStream os;
PdfImageObject image = renderInfo.getImage();
PdfImageObject tmp = null;
PdfName filter = (PdfName) image.get(PdfName.FILTER);
///
PdfDictionary imageDictionary = image.getDictionary();
// Try SMASK, SMASKINDATA
PRStream maskStream = (PRStream) imageDictionary.getAsStream(PdfName.SMASK);
// todo - required - black white - fix
PdfImageObject maskImage = new PdfImageObject(maskStream);
image = maskImage;
if (PdfName.DCTDECODE.equals(filter)) {
filename = String.format(path, renderInfo.getRef().getNumber(), "jpg");
os = new FileOutputStream(filename);
os.write(image.getImageAsBytes());
os.flush();
os.close();
} else if (PdfName.JPXDECODE.equals(filter)) {
filename = String.format(path, renderInfo.getRef().getNumber(), "jp2");
os = new FileOutputStream(filename);
os.write(image.getImageAsBytes());
os.flush();
os.close();
} else if (PdfName.JBIG2DECODE.equals(filter)) {
// ignore: filter not supported.
} else {
BufferedImage awtimage = renderInfo.getImage().getBufferedImage();
if (awtimage != null) {
filename = String.format(path, renderInfo.getRef().getNumber(), "png");
ImageIO.write(awtimage, "png", new FileOutputStream(filename));
}
}
try {
final String newfile = String.format(path, renderInfo.getRef().getNumber(), ".x.", "png");
BufferedImage bi = image.getBufferedImage();
BufferedImage newBi = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_USHORT_GRAY);
newBi.getGraphics().drawImage(bi, 0, 0, null);
ImageIO.write(newBi, "png", new FileOutputStream(newfile));
} catch(final Exception e) {
e.printStackTrace();;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static Image makeBlackAndWhitePng(PdfImageObject image) throws IOException, DocumentException {
BufferedImage bi = image.getBufferedImage();
BufferedImage newBi = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_USHORT_GRAY);
newBi.getGraphics().drawImage(bi, 0, 0, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(newBi, "png", baos);
return Image.getInstance(baos.toByteArray());
}
/**
* #see com.itextpdf.text.pdf.parser.RenderListener#renderText(
*com.itextpdf.text.pdf.parser.TextRenderInfo)
*/
public void renderText(TextRenderInfo renderInfo) {
}
}
And code around loading the pages
public static void readImages(final PdfReader reader, final File filex) throws IOException {
for (int i = 0; i < reader.getXrefSize(); i++) {
PdfObject pdfobj = reader.getPdfObject(i);
if (pdfobj == null || !pdfobj.isStream()) {
continue;
}
PdfStream stream = (PdfStream) pdfobj;
PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE);
if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) {
byte[] img = PdfReader.getStreamBytesRaw((PRStream) stream);
FileOutputStream out = new FileOutputStream(new File(filex.getParentFile(), String.format("%1$05d", i) + ".jpg"));
out.write(img);
out.flush();
out.close();
}
}
}
To combine my comments:
What you see, merely is the soft mask of the image which contains transparency information, white = opaque, black = transparent. The base image actually is all black but only where the mask indicates opaque, that image black is drawn. Thus it looks like reversed.
You can use image manipulation libraries to invert a bitmap. Simply googl'ing for "imageio invert image" returns this, this, and numerous other interesting matches.

Convert byte[] to com.itextpdf.text.Image error image==null

I am trying to convert the input byte[] image to com.itextpdf.text.Image because I need to put this 2 image in a pdf.
Here my code:
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PushbuttonField;
public class Tryit {
public static void main (String[] args) throws Exception
{
byte[] front = extractBytes("C:/Users/Desktop/Front.png");
byte[] back = extractBytes("C:/Users/Desktop/Back.png");
addImageToPdf(front,back);
}
public static byte[] extractBytes (String ImageName) throws IOException {
// open image
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
// get DataBufferBytes from Raster
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
return ( data.getData() );
}
public static void addImageToPdf(byte[] frontByte, byte[] backByte) throws IOException, DocumentException
{
ByteArrayInputStream bais = new ByteArrayInputStream(frontByte);
BufferedImage a = ImageIO.read(bais);
InputStream frontIn = new ByteArrayInputStream(frontByte);
BufferedImage bImageFromFront = ImageIO.read(frontIn);
InputStream backIn = new ByteArrayInputStream(backByte);
BufferedImage bImageFromBack = ImageIO.read(backIn);
ByteArrayOutputStream baosF = new ByteArrayOutputStream();
ImageIO.write(bImageFromFront, "png", baosF);
Image front = Image.getInstance(baosF.toByteArray());
ByteArrayOutputStream baosB = new ByteArrayOutputStream();
ImageIO.write(bImageFromBack, "png", baosB);
Image back = Image.getInstance(baosB.toByteArray());
PdfReader reader = new PdfReader("C:/Users/Desktop/Template.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("C:/Users/Desktop/P1.pdf"));
AcroFields form = stamper.getAcroFields();
PushbuttonField ad = form.getNewPushbuttonFromField("Front");
ad.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
ad.setProportionalIcon(true);
ad.setImage(front);
form.replacePushbuttonField("Front", ad.getField());
PushbuttonField ad1 = form.getNewPushbuttonFromField("Back");
ad1.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
ad1.setProportionalIcon(true);
ad1.setImage(back);
form.replacePushbuttonField("Back", ad1.getField());
stamper.setFormFlattening(true);
stamper.close();
reader.close();
}}
The error is here : BufferedImage bImageFromFront = ImageIO.read(frontIn); infact my bImageFromFront return null, so I have the error here
ImageIO.write(bImageFromFront, "png", baosF);
because my bImageFromFront is null. I don't understand why I have this error and why the conversion from bufferedImage to ImageIO returns null

Image Upload Image Preview

Hi everyone hope you can help me to display the preview image or thumbnail after selecting the image not after pressing the upload button. Hope you can help me guys! Thanks..
Profile Image Upload
This is my code for upload handler
here temp_storage_path is local application temp path
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import com.wcs.wcslib.vaadin.widget.multifileupload.ui.UploadFinishedHandler;
public class ImageUploadFinishedHandler implements UploadFinishedHandler {
VerticalLayout imageLayout;
public ImageUploadFinishedHandler(VerticalLayout imageLayout) {
this.imageLayout = imageLayout;
}
#Override
public void handleFile(InputStream stream, String fileName, String arg2, long arg3) {
File file = null;
try {
file = new File("temp_storage_path"+fileName);
OutputStream outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = stream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.close();
} catch (FileNotFoundException e) {
return;
} catch (IOException e) {
return;
}
this.imageLayout.removeAllComponents();
Image previewImage = new Image();
this.imageLayout.addComponent(previewImage);
previewImage.setWidth("100px");
previewImage.setHeight("100px");
previewImage.setSource(new FileResource(file));
}
}

How can a TIFF file be centered properly in a PDF file with the DIN A4 format?

The following program converts a TIF file to PDF file using itext-library (Version 2.1.7).
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.RandomAccessFileOrArray;
import com.lowagie.text.pdf.codec.TiffImage;
import java.io.File;
import java.io.FileOutputStream;
public class Tiff2Pdf {
public static File convert(String tifPath, String pdfPath) {
File pdfFile = null;
String imgeFilename = tifPath;
Document document = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(
document,
new FileOutputStream(pdfPath));
writer.setStrictImageSequence(true);
Image image;
document.open();
RandomAccessFileOrArray ra = new RandomAccessFileOrArray(imgeFilename);
int pagesTif = TiffImage.getNumberOfPages(ra);
for (int i = 1; i <= pagesTif; i++) {
image = TiffImage.getTiffImage(ra, i);
image.scaleAbsolute(PageSize.A4.getWidth(), PageSize.A4.getHeight());
Rectangle pageSize = new Rectangle(633, 842);
document.setPageSize(pageSize);
document.newPage();
document.add(image);
}
pdfFile = new File(pdfPath);
document.close();
PdfReader read = new PdfReader(pdfPath);
} catch (Exception ex) {
//do nothing
}
return pdfFile;
}
}
But the PDF file is not aligned centered.
How can the converted TIF file be aligned centrally in PDF file?
The solution is:
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.RandomAccessFileOrArray;
import com.lowagie.text.pdf.codec.TiffImage;
import java.io.File;
import java.io.FileOutputStream;
/**
*
* #author Rahman
*/
public class Tiff2Pdf {
public static File convert(String tif, String pdf) {
File pdfFile = null;
String imgeFilename = tif;
Document document = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(
document,
new FileOutputStream(pdf));
writer.setStrictImageSequence(true);
Image image;
document.open();
RandomAccessFileOrArray ra = new RandomAccessFileOrArray(imgeFilename);
int pagesTif = TiffImage.getNumberOfPages(ra);
for (int i = 1; i <= pagesTif; i++) {
image = TiffImage.getTiffImage(ra, i);
image.scaleAbsolute(PageSize.A4.getWidth(), PageSize.A4.getHeight());
document.setMargins(0, 0, 0, 0);
document.newPage();
document.add(image);
}
pdfFile = new File(pdf);
document.close();
} catch (Exception ex) {
//do nothing
}
return pdfFile;
}
}

Java Image Sending Network

I am trying to send Image over the Network following Server code.
import java.net.*;
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Server {
static private BufferedImage bi;
static Socket socket;
static ServerSocket serverSocket;
DataInputStream dis=null;
public static void connect() throws IOException
{
serverSocket = new ServerSocket(9632);
System.out.println("i am server & listening...");
socket = serverSocket.accept();
System.out.println("Connected");
}
public static void main (String [] args ) throws IOException {
connect();
receiveimage();
showimage();
}
public static void receiveimage()
{
byte[] data;
while (true){
try{
System.out.println("Reading Image");
InputStream in=socket.getInputStream();
data=new byte[socket.getReceiveBufferSize()];
in.read(data, 0, socket.getReceiveBufferSize());
Image image = getPhoto(data);
bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
}
catch(Exception ex)
{
System.out.println("error: " + ex.toString());
}
}
}
public static void showimage() throws IOException
{
File file = new File("saved.png");
Image image = ImageIO.read(file);
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(image));
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static Image getPhoto(byte[] bytePhoto) throws IOException {
return ImageIO.read(new ByteArrayInputStream(bytePhoto)); //bytePhoto is the byte array
}
}
and following Client code
import java.net.*;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class client{
public static byte[] bytePhoto;
public static Socket sock;
public static void connect() throws IOException
{
Socket sock = new Socket("172.16.0.143",9632);
System.out.println("Connected");
}
public static void main (String [] args ) throws IOException, ClassNotFoundException {
connect();
sendphoto();
}
public static void sendphoto() throws IOException
{
InputStream is = new BufferedInputStream(new FileInputStream("c:\\ziki.png"));
Image image = ImageIO.read(is);
byte[] data=setPhoto(image);
// OutputStream output = sock.getOutputStream();
//output.write(data);
}
public static byte[] setPhoto(Image img) throws IOException {
ImageIcon icon = new ImageIcon(img);
BufferedImage bImg = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = bImg.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
ByteArrayOutputStream writer = new ByteArrayOutputStream();
ImageIO.write(bImg, "jpg", writer);
return bytePhoto = writer.toByteArray(); //bytePhoto is a byte array
}
}
It is giving me Java Null pointer exception on Client side.
When I run this, I'm getting a NullPointerException on the server side. ImageIO.read in getPhoto is returning null, because I don't have an ImageReader registered that's capable of reading the stream.
Any ImageInputStreamSpis in your classpath are automatically registered, so I guess I don't have one. I don't know what's installed on your machine, but it's likely a similar problem.

Categories