I am capturing a person image passport using webcam lib.The genereated image is infor of png. I want to create a temporaly png file then convert that png file into JPG2000 format. How can I achieve this in java? here is my sample code n java
webcam.open();
BufferedImage image = webcam.getImage();
imagePath = "";
File temppngfile = new File(imagePath);
ImageIO.write(image, "png", temppngfile);
Related
Displaying an image in base64 is rather simple:
<img src="data:image/png;base64,hexadecimal-code-for-image-here">
However, what I'm trying to do is to convert the hexadecimal value received and the save it in a png file so I get the desired picture from the code.
For instance: let's say I have the following code:
iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABmJLR0QAAAAAAAD5
Q7t/AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3wEVDTYmJtINnAAAAcRJ
REFUOMuVlL9rU1EUx7/n3psmL6VoWqoJpNgI0Vg6uXSw0E0QHBzsUJDSoSKCuLro
KIL0D3Dr2N0gOHUpdWgrLW0EW5osakNT+4Oo7+X13XuPi4L2SZ73jGf43O/hfM4l
nKnC9TtZmStfIwKFn5bXW9vvDBxKnG2YdP7BzOzDtanp+6uBGLwFx1LxF7RtHvmI
tIaUsK7AWEJW6UgbC2MYxtjQFUijky/Hy5WROQIgBbgT6nyuUBo2hvGtVf8oVPrE
GCbDwM6Hjce71WcrXUfuv1C8lC9eHiMwlCCcGgs/1CBiFEuVShhZBKcGHQ309H0e
AtAd+PXwkFa36shkPCglIaXEcOE8jABqjQMQgEhrdAIfZCNKHFmlsr3C6yuzjaCD
tr56++m9GzfvPgEDr+efPzquVZco5QkhFcJ2cxuMoGtCHfk/EPkbvxsD+dJejyIA
jMzFkYZ+v7CJ8Pt/exrbMhFoaCCNYn8G2gpy9TTm4cF+U7xZ+QIAyHKbXD2NARtv
X7w6rk8sghmtrWrN1dPErbl6qpKArp4mAl09TRzZ1dPEhK6eKuff5JenzPinp87A
JE/JFZjyznm58sSVPzz96/R+AmVHLPIJpOvnAAAAAElFTkSuQmCC
Is there any way I can convert this code to image and then store in a png file in JAVA?
Transfer the base64 into byte array and than write it to a png file.
byte[] img = Base64.getDecoder().decode(imgBase64);
Files.write(Paths.get("my.png"), img); //As suggested by Joop Eggen
Decode base64 image to byte[] then using ImageIO to write to file
byte[] imgInBytes = Base64.getDecoder().decode(base64Img);
InputStream in = new ByteArrayInputStream(imgInBytes);
BufferedImage bufferedImage = ImageIO.read(in);
File png = new File("ImageAsPNG.png");
ImageIO.write(bufferedImage, "PNG", png);
So as the title says I am looking for a way to turn SVG to PNG with Apache Batik and then attach this image to PDF file using PDFBox without actually creating the svg and png anywhere.
Currently I have a web form that has SVG image with selectable parts of it.
When the form is submitted I take the "html" part of the svg meaning I keep something like <svg bla bla> <path bla bla/></svg> in a string that Spring then uses to create a ".svg" file in a given folder, then Batik creates a PNG file in the same folder and then PDFBox attaches it to the PDF - this works fine(code below).
//Get the svg data from the Form and Create the svg file
String svg = formData.getSvg();
File svgFile = new File("image.svg");
BufferedWriter writer = new BufferedWriter(new FileWriter(svgFile));
writer.write(svg);
writer.close();
// Send to Batik to turn to PNG
PNGTranscoder pngTranscode = new PNGTranscoder();
File svgFile = new File("image.svg");
InputStream in = new FileInputStream(svgFile);
TranscoderInput tIn = new TranscoderInput(in);
OutputStream os = new FileOutputStream("image.png");
TranscoderOutput tOut = new TranscoderOutput(os)
pngTranscode .transcode(tIn , tOut);
os.flush();
os.close();
//Send to PDFBox to attach to pdf
File pngfile = new File("image.png");
String path = pngfile.getAbsolutePath();
PDImageXObject pdImage = PDImageXObject.createFromFile(path, pdf);
PDPageContentStream contents = new PDPageContentStream(pdf, pdf.getPage(1));
contents.drawImage(pdImage, 0, pdf.getPage(1).getMediaBox().getHeight() - pdImage.getHeight());
contents.close();
As you can see there are a lot of files and stuff (need to tidy it up a bit), but is it possible to do this on the run without the creation and constant fetching of the svg and png files?
Given the suggestion in the comments I opted for using ByteArrayOutputStream, ByteArrayInputStream, BufferedImage and LosslessFactory. Its a bit slower than the saving (if you go through it in debug as seems the BufferedImage goes on a holiday first before creating the image).
The sources I found to use are: How to convert SVG into PNG on-the-fly and Print byte[] to pdf using pdfbox
byte[] streamBytes = IOUtils.toByteArray(new ByteArrayInputStream(formData.getSvg().getBytes()));
PNGTranscoder pngTranscoder = new PNGTranscoder();
ByteArrayOutputStream os = new ByteArrayOutputStream();
pngTranscoder.transcode(new TranscoderInput(new ByteArrayInputStream(streamBytes)), new TranscoderOutput(os));
InputStream is = new ByteArrayInputStream(os.toByteArray());
BufferedImage bim = ImageIO.read(is);
PDImageXObject pdImage = LosslessFactory.createFromImage(pdf, bim);
PDPageContentStream contents = new PDPageContentStream(pdf, pdf.getPage(1));
contents.drawImage(pdImage, 0, pdf.getPage(1).getMediaBox().getHeight() - pdImage.getHeight());
contents.close();
Based on the comments and links provided by D.V.D., I also worked through the problem. I just wanted to post the simple but full example, for anyone wanting to review in the future.
public class App {
private static String OUTPUT_PATH = "D:\\so52875145\\output\\PdfWithPngImage.pdf";
public static void main(String[] args) {
try {
// obtain the SVG source (hardcoded here, but the OP would obtain the String from form data)
byte[] svgByteArray = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"><polygon points=\"200,10 250,190 160,210\" style=\"fill:lime;stroke:purple;stroke-width:1\" /></svg>".getBytes();
System.out.println("Converted svg to byte array...");
// convert SVG into PNG image
PNGTranscoder pngTranscoder = new PNGTranscoder();
ByteArrayOutputStream os = new ByteArrayOutputStream();
pngTranscoder.transcode(new TranscoderInput(new ByteArrayInputStream(svgByteArray)), new TranscoderOutput(os));
System.out.println("Transcoded svg to png...");
// create PDF, and add page to it
PDDocument pdf = new PDDocument();
pdf.addPage(new PDPage());
// generate in-memory PDF image object, using the transcoded ByteArray stream
BufferedImage bufferedImage = ImageIO.read( new ByteArrayInputStream(os.toByteArray()) );
PDImageXObject pdImage = LosslessFactory.createFromImage(pdf, bufferedImage);
System.out.println("Created PDF image object...");
// write the in-memory PDF image object to the PDF page
PDPageContentStream contents = new PDPageContentStream(pdf, pdf.getPage(0));
contents.drawImage(pdImage, 0, 0);
contents.close();
System.out.println("Wrote PDF image object to PDF...");
pdf.save(OUTPUT_PATH);
pdf.close();
System.out.println("Saved PDF to path=[" + OUTPUT_PATH + "]");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to create pdf in java using pdfbox 1.8, but problem is I am not able to show CMYK image on pdf so I try to solution on same like below code:
File filePath = new File("C:/Users/msuryawanshi/Documents/10734730431625_C1LA.jpg");
JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(new FileInputStream(filePath));
BufferedImage image = jpegDecoder.decodeAsBufferedImage();
imageUrl = "http://extranet.handgards.com/gs1/10734730431625_C1LA.jpg";
File f = new File("C:/Users/msuryawanshi/Documents/10734730431625_C1LA.jpg");
String url = "http://extranet.handgards.com/gs1/10734730431625_C1LA.jpg";
Iterator readers = ImageIO.getImageReadersByFormatName("JPEG");
ImageReader reader = null;
while (readers.hasNext()) {
reader = (ImageReader) readers.next();
if (reader.canReadRaster()) {
break;
}
}
//Stream the image file (the original CMYK image)
ImageInputStream input = ImageIO.createImageInputStream(f);
reader.setInput(input);
//Read the image raster
Raster raster = reader.readRaster(0, null);
//Create a new RGB image
BufferedImage bi = new BufferedImage(raster.getWidth(), raster.getHeight(),
BufferedImage.TYPE_4BYTE_ABGR);
//Fill the new image with the old raster
bi.getRaster().setRect(raster);
PDXObjectImage ximage = new PDPixelMap(document, bi);
contentStream.drawXObject(ximage, margin + 5, texty, 170, 100);
but image is not meaningful, I have attached output pdf and original image which i want display on my pdf. please help for the same.
PDFBox doesn't support embedding CMYK images at all because java itself can't read such images. You might be able to embed it as an RGB image by using the twelvemonkeys library instead of Java ImageIO to read the JPEG into a BufferedImage. From there, just use PDPixelMap (in 1.8) or LosslessFactory (in 2.0).
I need help to convert a .BMP image to .gif .
I am struggling with preserving the quality of the the converted gif image. I need help here . Following is the related code. Any help is appreciated.
//now Convert the names to lower case and change the extension to the file as a .gif file under the images directory
//you can either use URL or File for reading image using ImageIO
bufferedSourceImg = ImageIO.read(fSource);
//getting the RGB mode color value
int color = bufferedSourceImg.getRGB(0,0);
Image image = makeColorTransparent(bufferedSourceImg,new Color(color));
//getting the transparent image
BufferedImage transparent = imageToBufferedImage(image);
//generating the name of the gif image which will be created from the bmp
int idx = destFName.lastIndexOf(".");
destFName = destFName.substring(0, idx);
destFName = destFName + ".gif";
gifFile = new File(getImagesDirectory(), destFName);
//copying the gif copy of the image
Iterator itr = ImageIO.getImageWritersByFormatName("gif");
ImageWriter gifWriter = (ImageWriter)itr.next();
ImageWriteParam iwp = gifWriter.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
String compTypes[] = iwp.getCompressionTypes();
iwp.setCompressionType(compTypes[compTypes.length - 1]);
iwp.setCompressionQuality(0);
//ImageIO.write(transparent, "gif", gifFile);
ImageIO.write(bufferedSourceImg, "gif", gifFile);
FileImageOutputStream output = new FileImageOutputStream(gifFile);
gifWriter.setOutput(output);
IIOImage iioImage = new IIOImage(transparent, null, null);
gifWriter.write(null, iioImage, iwp);
gifWriter.dispose();
In Java, I have to crop and rotate an image in scanned pdf file and create another pdf file with the result image
For example, I have the image1 and want get the image2 centered in the page as result
How can I proceed?
Thanks!
The pdf is a scanned file.
It contains for example a student card.
I have to rotate the stutend card scanned on the right way and centered it in the A4 page.
I try to get the image like this :
PDDocument docIn = null;
File inputPdfFile = new File("C:\\test.pdf");
File output = new File("C:\\testOutput.png");
try {
// Read the pdf into a BufferedImage
docIn = PDDocument.load(inputPdfFile);
List<PDPage> pages = docIn.getDocumentCatalog().getAllPages();
PDPage page = pages.get(0);
// get the image
BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
ImageIO.write(image, "png", output);
} catch (IOException e) {
e.printStackTrace();
}
Then, I use the javaxt librairies to trim the image
Image image = new Image(output);
image.trim();
image.saveAs("C:\\projetCrop\\trimImage.png");
Now, how to detect the rotation angle?