Unable to resize image on word document - java

We are getting image as a byte array and encode it into base64 string then writing this string into word doc but unable to change it's size.
PFB code:
worddocfile // stringbuilder
String encodedImage = new String(Base64.encodeBase64(fileType.getFileContent()), "UTF-8");
encodedImage = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
worddocfile.append("<img style='display:block; width:600px;height:600px;' id='base64image'")
.append(" src='data:image/jpeg;base64,")
.append(encodedImage)
.append("' /> ");
Can anyone suggest the solution because it's working on html page but not on word document.
We have already used background image tag but it's not working.
<p style="background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='); border: 1px solid black;background-repeat: no-repeat;background-size: contain;width:600px;height:597px;\>

Convert byte array into an image and place this image inside the WEB-INF folder.
Now re scale the converted image with the updated size and store it inside WEB-INF folder.
Now convert the re scaled image into byte array and write the bytes on the word doc.
PFB the code:
ByteArrayInputStream bis1 = new ByteArrayInputStream(fileType.getFileContent() );
Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
//ImageIO is a class containing static methods for locating ImageReaders
//and ImageWriters, and performing simple encoding and decoding.
ImageReader reader = (ImageReader) readers.next();
Object source1 = bis1;
ImageInputStream iis = ImageIO.createImageInputStream(source1);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
try{
Image image1 = reader.read(0, param);
//got an image file image1 -- image1.getWidth(null)
BufferedImage bufferedImage = new BufferedImage(650,950, BufferedImage.TYPE_INT_RGB);
//bufferedImage is the RenderedImage to be written
Graphics2D g2 = bufferedImage.createGraphics();
g2.setBackground(Color.WHITE);
g2.clearRect(0, 0, 650,950);
g2.drawImage(image1, 0,0,650,950, null);//
g2.dispose();
//mgpath can be WEB-INF folder
File imageFile = new File(imgpath+"UpdatedImg.jpg");
ImageIO.write(bufferedImage, "jpg", imageFile);
FileInputStream fisn = new FileInputStream(imageFile);
//create FileInputStream which obtains input bytes from a file in a file system
//FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
ByteArrayOutputStream bosn = new ByteArrayOutputStream();
byte[] bufn = new byte[1024];
try {
for (int readNum1; (readNum1 = fisn.read(bufn)) != -1;) {
//Writes to this byte array output stream
bosn.write(bufn, 0, readNum1);
System.out.println("read " + readNum1 + " bytes,");
}
} catch (IOException ex) {
}
byte[] outArray1 = bosn.toByteArray();
String encodedImage = new String(Base64.encodeBase64(outArray1), "UTF-8");
logger.debug("encodedImage" + encodedImage);
/// workbookDetails.append("<img src='data:image/png;base64," + encodedImage + "'/>");
workbookDetails.append("<img style='display:block; width:595px;height:609px;' id='base64image'")
.append(" src='data:image/jpeg;base64,")
.append(encodedImage)
.append("' /> ")
.append(" </p>")
.append(" </td>")
.append(" </tr>")
.append(" </tbody>")
.append("</table>");
.append("</table>");

Related

How to reduce PNG/JPEG file size in spring boot

I want to reduce the file size while saving the image.
Please, take this code for reference.
And how to reduce the file size.
public void saveImage(MultipartFile image_one, MultipartFile image_two, MultipartFile image_three) throws Exception{
System.out.println("Inside Save image Repo");
String folder = "C:/Users/HP/Photos";
byte[] bytes_one;
try {
bytes_one = image_one.getBytes();
Path path1 = Paths.get(folder + image_one.getOriginalFilename());
System.out.println("Path of 1st imagae : "+path1);
Files.write(path1, bytes_one);
System.out.println("Image-1 size : "+bytes_one.length);
} catch (Exception e) {
System.out.println("Inside Catch Block -> Image not found ");
e.printStackTrace();
}
}
You could use the Java javax.imageio library and use a function to compress your image bytes.
This should do the work:
public byte[] compressImage(MultipartFile image) throws IOException
{
InputStream inputStream = image.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
float imageQuality = 0.3f;
// Create the buffered image
BufferedImage bufferedImage = ImageIO.read(inputStream);
// Get image writers
Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("jpg"); // Input your Format Name here
if (!imageWriters.hasNext())
throw new IllegalStateException("Writers Not Found!!");
ImageWriter imageWriter = imageWriters.next();
ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);
imageWriter.setOutput(imageOutputStream);
ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
// Set the compress quality metrics
imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
imageWriteParam.setCompressionQuality(imageQuality);
// Compress and insert the image into the byte array.
imageWriter.write(null, new IIOImage(bufferedImage, null, null), imageWriteParam);
byte[] imageBytes = outputStream.toByteArray();
// close all streams
inputStream.close();
outputStream.close();
imageOutputStream.close();
imageWriter.dispose();
return imageBytes;
}
It returns the compressed image bytes so that the value returned can be transformed into a number of things. In your case, in a file...
byte[] compressedImageBytes = compressImage(imageOne);
Files.write(path1, bytesOne);

Java : PDF page preview error, expected xref

I am trying to create a preview for PDF files which are created by Ballasamic Mockups. Around 50% of the time, I am not getting a preview and getting xref missing error. What am I doing wrong?
Error log :
com.sun.pdfview.PDFParseException: Expected 'xref' at start of table
at com.sun.pdfview.PDFFile.readTrailer(PDFFile.java:974)
at com.sun.pdfview.PDFFile.parseFile(PDFFile.java:1175)
at com.sun.pdfview.PDFFile.<init>(PDFFile.java:126)
at com.sun.pdfview.PDFFile.<init>(PDFFile.java:102)
Code :
private byte[] onlyCreatePdfPreview(String path, int attachId) {
try {
File file = new File(path);
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new com.sun.pdfview.PDFFile(buf);
PDFPage page = pdffile.getPage(0);
Rectangle rect = new Rectangle(0, 0,
(int) page.getBBox().getWidth(),
(int) page.getBBox().getHeight());
java.awt.Image img = page.getImage(
rect.width, rect.height, //width & height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
BufferedImage buffered = toBufferedImage(img);
buffered = Scalr.resize(buffered, Scalr.Method.ULTRA_QUALITY, 400, 250);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffered, "png", baos);
baos.flush();
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
}
What am I doing wrong? Thank you.
Final Working code
try {
String pdfPath = zipLocation + String.valueOf(new BigInteger(130, random).toString(32));
PdfReader reader = new PdfReader(path);
PdfStamper pdfStamper = new PdfStamper(reader,new FileOutputStream(pdfPath));
pdfStamper.getWriter().setPdfVersion(PdfWriter.PDF_VERSION_1_4);
pdfStamper.close();
reader.close();
RandomAccessFile raf = new RandomAccessFile(pdfPath, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new com.sun.pdfview.PDFFile(buf);
PDFPage page = pdffile.getPage(0);
Rectangle rect = new Rectangle(0, 0,
(int) page.getBBox().getWidth(),
(int) page.getBBox().getHeight());
java.awt.Image img = page.getImage(
rect.width, rect.height, //width & height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
BufferedImage buffered = toBufferedImage(img);
buffered = Scalr.resize(buffered, Scalr.Method.ULTRA_QUALITY, 400, 250);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffered, "png", baos);
baos.flush();
return baos.toByteArray();
}//catch block
(This answer collects information from comments to the question which eventually led to a solution.)
Apparently com.sun.pdfview.PDFFile expects the cross references to start with xref. But this expectation only makes sense for PDFs following a PDF Reference up to revision 3 (version 1.4) published November 2001; PDFs following a later Reference or even the ISO 32000 standard (part 1 or 2) have the choice of using a cross reference stream (starting with an object number) instead of a cross reference table (starting with xref).
Thus, one should switch to using software following newer specifications than some more than 15 years old version or one has to convert one's PDFs to follow the old specifications, at least on the surface.
One can convert manually (e.g. using Adobe Acrobat) or automatized (e.g. using iText). (These examples software products really are only examples, other products can also be used for this task.)
If using a current iText 5 version, the conversion looks like this:
PdfReader reader = new PdfReader(SOURCE);
PdfStamper stamper = new PdfStamper(reader, DEST);
stamper.getWriter().setPdfVersion(PdfWriter.PDF_VERSION_1_4);
stamper.close();
reader.close();
And one has to take care that if SOURCE is a file name or a random access file, DEST must not be a file output stream to the same file. Otherwise the original file is truncated before the PdfStamper had a chance to copy it all to its output.

Liferay DLFileEntry image conversion is not fully converting the image

I am converting an image as a DLFileEntry from JPG to PNG format using the following code.
try {
DLFileEntry dlFileEntry = DLFileEntryServiceUtil.getFileEntry(dlFileEntryId);
InputStream inputStream = dlFileEntry.getContentStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] byteArray = buffer.toByteArray();
ImageBag imageBag = ImageToolUtil.read(byteArray);
RenderedImage renderedImage = imageBag.getRenderedImage();
if (renderedImage == null) {
throw new IOException("Unable to decode image");
}
renderedImage = ImageToolUtil.scale(renderedImage, 2000);
buffer = new ByteArrayOutputStream();
ImageIO.write(renderedImage, "png", buffer);
InputStream fis = new ByteArrayInputStream(buffer.toByteArray());
DLAppServiceUtil.updateFileEntry(
dlFileEntry.getFileEntryId(),
dlFileEntry.getName(),
MediaType.IMAGE_PNG_VALUE,
dlFileEntry.getTitle(),
dlFileEntry.getDescription(),
"",
true,
fis,
buffer.size(),
serviceContext);
} catch (Exception e) {
e.printStackTrace();
}
Even though it updates the image content type and extension in "Documents and Media", when we try downloading the image, it is still in JPG format.
The image looks like above in Documents and Media. You can see that the content type has become image/png.
Above shows the screenshot while I tried to Download this image and save it. It is still in the original format of JPG when I try downloading. What should I do in addition to the code above, inorder to completely convert the image to PNG?
You still store the old file name: dlFileEntry.getName()
I would guess that jpeg or jpg is the extension of the old file name and the browser determines his file filter from the extension.
So better exchange the extension as well:
DLAppServiceUtil.updateFileEntry(
dlFileEntry.getFileEntryId(),
dlFileEntry.getName().replaceAll("\\..*?$",".png"),
...
This will change the extension that is stored for that file

Error converting PNG to TIFF-Java

HI I am working on the following snippet which is supposed to convert my png file to tiff.
String fileName = "4848970_1";
// String fileName = "color";
String inFileType = ".PNG";
String outFileType = ".TIFF";
File fInputFile = new File("C:\\Users\\abc\\Downloads\\image2.png");
InputStream fis = new BufferedInputStream(new FileInputStream(fInputFile));
ImageReaderSpi spi = new PNMImageReaderSpi();
ImageReader reader = spi.createReaderInstance();
ImageInputStream iis = ImageIO.createImageInputStream(fis);
reader.setInput(iis, true);
BufferedImage bi = reader.read(0);
int[] xi = bi.getSampleModel().getSampleSize();
for (int i : xi) {
System.out.println("bitsize " + i);
}
ImageWriterSpi tiffspi = new TIFFImageWriterSpi();
TIFFImageWriter writer = (TIFFImageWriter) tiffspi.createWriterInstance();
// TIFFImageWriteParam param = (TIFFImageWriteParam) writer.getDefaultWriteParam();
TIFFImageWriteParam param = new TIFFImageWriteParam(Locale.US);
String[] strings = param.getCompressionTypes();
for (String string : strings) {
System.out.println(string);
}
//param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
//param.setCompressionType("LZW");
File fOutputFile = new File("C:\\Users\\abc\\Downloads\\" + fileName + outFileType);
OutputStream fos = new BufferedOutputStream(new FileOutputStream(fOutputFile));
ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
writer.setOutput(ios);
writer.write(null, new IIOImage(bi, null, null), param);
ios.flush();
writer.dispose();
ios.close();
But this gives me following error
Exception in thread "main" java.lang.RuntimeException: What in the stream isn't a PNM image.
at com.sun.media.imageioimpl.plugins.pnm.PNMImageReader.readHeader(PNMImageReader.java:187)
at com.sun.media.imageioimpl.plugins.pnm.PNMImageReader.read(PNMImageReader.java:301)
at javax.imageio.ImageReader.read(Unknown Source)
at com.imageconv.TiffImage.main(TiffImage.java:40)
Is it that its unable to read the PNG file or it recognises it as a non png file.Am I wrong anywhere?
You are trying to read a PNG image as if it was a PNM image. These two file formats have nothing in common; hence the error.

Using ImageIO to write JPEG 2000 with layers (i.e. decomposition levels)

Ok, here is our issue:
We are trying to convert a series of black and white .tiff files into jpeg2000 .jpf files, using imageio. We are always getting viewable .jpf files, but they usually do not have the specified number of layers or decomposition levels for zooming.
Here is our code:
//Get the tiff reader
Iterator<ImageReader> readerIterator = ImageIO.getImageReadersByFormatName("tiff");
ImageReader tiffreader = readerIterator.next();
//make an ImageInputStream from our tiff file and have the tiff reader read it
ImageInputStream iis = ImageIO.createImageInputStream(itemFile);
tiffreader.setInput(iis);
//just pass empty params to the tiff reader
ImageReadParam tparam;
tparam = new TIFFImageReadParam();
IIOImage img = tiffreader.readAll(0, tparam);
//set up target file
File f = new File(itemTargetDirectory.getAbsolutePath() + "/" + destFileName);
//we have tried FILTER_97 as well as different ProgressionTypes and compression settings
J2KImageWriteParam param;
param = new J2KImageWriteParam();
param.setProgressionType("layer");
param.setFilter(J2KImageWriteParam.FILTER_53);
//Our problem is that this param is not always respected in the resulting .jpf
param.setNumDecompositionLevels(5);
//get the JPEG 2000 writer
Iterator<ImageWriter> writerIterator = ImageIO.getImageWritersByFormatName("JPEG 2000");
J2KImageWriter jp2kwriter = null;
jp2kwriter = (J2KImageWriter) writerIterator.next();
//write the jpf file
ImageOutputStream ios = ImageIO.createImageOutputStream(f);
jp2kwriter.setOutput(ios);
jp2kwriter.write(null, img, param);
It has been an odd experience, as the same code has behaved differently on subsequent runs.
Any insights will be appreciated!
Do all the TIFF files have the same settings (color model)? J2KImageWriter.java shows the decomposition levels getting set (forced) to zero when indexed-color or multi-pixel packed source images are used as input.
Drew was on the right track, and here is the code that ended up sorting things out for us:
public void compressor(String inputFile, String outputFile) throws IOException {
J2KImageWriteParam iwp = new J2KImageWriteParam();
FileInputStream fis = new FileInputStream(new File(inputFile));
BufferedImage image = ImageIO.read(fis);
fis.close();
if (image == null)
{
System.out.println("If no registered ImageReader claims to be able to read the resulting stream");
}
Iterator writers = ImageIO.getImageWritersByFormatName("JPEG2000");
String name = null;
ImageWriter writer = null;
while (name != "com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriter") {
writer = (ImageWriter) writers.next();
name = writer.getClass().getName();
System.out.println(name);
}
File f = new File(outputFile);
long s = System.currentTimeMillis();
ImageOutputStream ios = ImageIO.createImageOutputStream(f);
writer.setOutput(ios);
J2KImageWriteParam param = (J2KImageWriteParam) writer.getDefaultWriteParam();
IIOImage ioimage = new IIOImage(image, null, null);
param.setSOP(true);
param.setWriteCodeStreamOnly(true);
param.setProgressionType("layer");
param.setLossless(false);
param.setCompressionMode(J2KImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("JPEG2000");
param.setCompressionQuality(0.1f);
param.setEncodingRate(1.01);
param.setFilter(J2KImageWriteParam.FILTER_97);
writer.write(null, ioimage, param);
System.out.println(System.currentTimeMillis() - s);
writer.dispose();
ios.flush();
ios.close();
image.flush();
}

Categories