Large image not displaying in Excel using Apache POI - apache-poi

I am trying to paste a 'JPEG' image file to Excel 2013 32-bit version. But after writing the workbook when I am opening it I am getting an error "The image cannot currently be displayed". The image file is very large.
I am using Windows 7 64 bit with Microsoft Excel 32 bit verison.
here is the portion of code to paste the image following the apache POI documentation. -
XSSFDrawing drawing = sheet.createDrawingPatriarch();
InputStream graphImage = new FileInputStream(fileName);
//Byte array to store the Image in Byte format
byte[] bytes = IOUtils.toByteArray(graphImage);
//Image Id
int imageId = frameWorkbook.addPicture(bytes,Workbook.PICTURE_TYPE_JPEG);
graphImage.close();
//Instance of ClientAnchor
ClientAnchor anchor = new XSSFClientAnchor();
anchor.setAnchorType(ClientAnchor.DONT_MOVE_AND_RESIZE);
//Setting start position of the Image
anchor.setCol1(5);
anchor.setRow1(5);
//Instance of XSSFpicture to paint the image
XSSFPicture picOfGraph = drawing.createPicture(anchor,imageId);
picOfGraph.resize();
This code works fine with small size image but if the image size gets larger then I am getting the error????Any solution??

Related

Convert pptx to images using java

i try to write a java program, which converts the pptx to jpeg images. There are many options (e.g., aspose, groupdocs, cloudmersive). But they are limited (either generating images in the evaluation mode or limited by the number of API calls); i prefer an open source library and up till now, i have known 2 libreries which are Apache POI and Docx4j. By using the Apache POI, i was able to implement the conversion PPTX-JPEG; however, the generated images' quality is low even the rendering parameters were set.
// create an empty presentation
public static void Pptx_Img(String slidePath, String outputDir, String fileName) throws Exception {
// create an empty presentation
File file = new File(slidePath);
FileInputStream in = new FileInputStream(file);
XMLSlideShow ppt = new XMLSlideShow(in);
// get the dimension and size of the slide
Dimension pgsize = ppt.getPageSize();
List<XSLFSlide> slides = ppt.getSlides();
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(1f);
BufferedImage img = null;
outputDir = outputDir + "\\apache\\pptx\\" + fileName;
Apache.createDirIfNotExists(outputDir);
for (int i = 0; i < 10; i++) {
img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
graphics.setRenderingHint(Drawable.BUFFERED_IMAGE, new WeakReference<>(img));
// clear area
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// draw the images
slides.get(i).draw(graphics);
FileOutputStream out = new FileOutputStream(outputDir + "\\slide_" + i + ".jpg");
/*
// specifies where the jpg image has to be written
final ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
writer.setOutput(ImageIO.createImageOutputStream(out));
// writes the file with given compression level
writer.write(null, new IIOImage(img, null, null), jpegParams);
*/
ImageIO.write(img, "jpeg", out);
ppt.write(out);
graphics.dispose();
out.close();
img.flush();
}
System.out.println("Images successfully created");
in.close();
ppt.close();
}
Comparison between the original slide and the generated images
I also came up with another indirect way, which converts pptx-pdf-jpeg (because i have the implementation for conversion pdf-jpeg and the conversion can actually maintain the image quality). But i couldnt find any open source libs which can do the conversion pptx-jpeg. For Apache POI, it can convert pptx-pdf but the mechanism is just similar to pptx-jpeg: writes the Graphic2D-instance to pdf instead of jpeg, which basically does not improve the rendering quality.
Added: Regarding to the comparison, the wrong rendering is also another issue !

Apache POI insert image without anchor

I'm creating Excel file in Java using Apache POI, it works but the inserted image is anchored to columns / rows. There are 2 issues with this method:
The image doesn't keep the original size (get stretched a little bit).
When resizing the columns/rows the image get stretched. Is there any way to insert an image to Excel without anchor? (same as using Excel / Insert / Picture)
I'm using the following example from Apache POI document page:
//create a new workbook
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
//add picture data to this workbook.
InputStream is = new FileInputStream("image1.jpeg");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
is.close();
CreationHelper helper = wb.getCreationHelper();
//create sheet
Sheet sheet = wb.createSheet();
// Create the drawing patriarch. This is the top level container for all shapes.
Drawing drawing = sheet.createDrawingPatriarch();
//add a picture shape
ClientAnchor anchor = helper.createClientAnchor();
//set top-left corner of the picture,
//subsequent call of Picture#resize() will operate relative to it
anchor.setCol1(3);
anchor.setRow1(2);
Picture pict = drawing.createPicture(anchor, pictureIdx);
//auto-size picture relative to its top-left corner
pict.resize();
//save workbook
String file = "picture.xls";
if(wb instanceof XSSFWorkbook) file += "x";
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();
Thanks for your answer.
Proably that because of this comment in method 'resize' javadoc:
Please note, that this method works correctly only for workbooks with the default font size (Arial 10pt for .xls and Calibri 11pt for .xlsx). If the default font is changed the resized image can be streched vertically or horizontally.

Issues when writing an image

Am into an J2ME project right now where I need to select an image and write this image to a particular folder say somewhere in memory card with a desired file name. Am able to select image and display it but when trying to save it am having trouble. When I try to save, an image file is created but its size is 0.0 kb and when I click on the image it says "File Format not supported"
This is my code
fileCon = (FileConnection)Connector.open(path+"Contacts/contactImages/"+FIRST_NAME+".png",Connector.READ_WRITE);
if(!fileCon.exists())
{
fileCon.create();
}
int h = contactImage.getHeight();
int w = contactImage.getWidth();
int[] size = new int[w*h];
contactImage.getRGB(size, 0, w, 0, 0, w, h);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
for (int i = 0; i < size.length; i++)
{
dos.writeInt(size[i]);
}
But you are writing pixel data into (in-memory) ByteArrayOutputStream, and not a file stream. Shouldn't there be something like
DataOutputStream dos = fileCon.openDataOutputStream();
And of course output stream should be closed to make sure all data is flushed.
Another thing is that you are saving raw ARGB data and not encoded PNG image, so .png extension may confuse some image viewers. Perhaps .bmp would be better.

PDFsharp edit a pdf file

Environment - PDFsharp Library, Visual Studio 2012 and C# as the language.
I am trying to:
read Test1.pdf (Width = 17 inches, Height – 11 inches) with 1 page
add some text to it
save it as another file (Test2.pdf)
I am able to do all the following. But when I open the file Test2.pdf the size of the page is getting reduced to Width = 11 inches, Height – 11 inches.
These PDF files that I am using are Product Specification Sheets that I have downloaded from the internet. I believe this is happening on only certain types of file and I am not sure how to differentiate these files.
Code given below:
//File dimentions - Width = 17 inches, Height - 11 inches (Tabloid Format)
PdfDocument pdfDocument = PdfReader.Open(#"D:\Test1.pdf", PdfDocumentOpenMode.Modify);
PdfPage page = pdfDocument.Pages[0];
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
//When the file is saved dimentions change to - Width = 11 inches, Height - 11 inches
pdfDocument.Save(#"D:\Test2.pdf");
I have uploaded the file here Test1.pdf
==================================================================================
As suggested by the PDFsharp Team the code should be as follows:
PdfDocument PDFDoc = PdfReader.Open(#"D:\Test1.pdf", PdfDocumentOpenMode.Import);
PdfDocument PDFNewDoc = new PdfDocument();
for (int Pg = 0; Pg < PDFDoc.Pages.Count; Pg++)
{
PdfPage pp = PDFNewDoc.AddPage(PDFDoc.Pages[Pg]);
XGraphics gfx = XGraphics.FromPdfPage(pp);
XFont font = new XFont("Arial", 10, XFontStyle.Regular);
gfx.DrawString("Hello, World!", font, XBrushes.Black, new XRect(0, 0, pp.Width, pp.Height), XStringFormats.BottomCenter);
}
PDFNewDoc.Save(#"D:\Test2.pdf");
Instead of modifying the document, please create a new document and copy the pages from the old document to the new document.
Sample code can be found in this post on the PDFsharp forum:
http://forum.pdfsharp.net/viewtopic.php?p=2637#p2637

view RGBA image

Can someone tell me how can I view an RGBA image? I just want a tool that I can display an RGBA image with!
I have written a code, which outputs only RGBA format. I just want to verify if my code worked, and just want to find a simple tool to view this image.
I wasn't able to come across a software to be able to display a RGBA image.
Thanks in advance.
RGBA files only contain raw channel data. The binary data will not have enough information to display an image (ie. width,height,depth, &tc).
If you know the image dimensions of each .rgba file, you should be able to work with the data. Here's an example of viewing raw date in javascript.
var fr = new FileReader(),
myWidth = 200,
myHeight = 200;
fr.onload = function(frEvent) {
var canvasElement = document.getElementById("myCanvas"),
ctx = canvasElement.getContext("2d"),
blob = ctx.createImageData(myWidth,myHeight),
index = 0;
while(index < frEvent.target.result.length)
blob.data[index] = frEvent.target.result.charCodeAt(index++);
ctx.putImageData(blob,0,0);
}
Imagemagick will be able to display raw RGBA data. Assuming that each color sample is 8 bits.
display -size 200x200 -depth 8 mySimpleData.rgba

Resources