We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Unable to add picture from stream

Hi,
i’m trying to add a picture from ByteArrayInputStream into the worksheet using the following code:

        BufferedImage image = getImage();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write( image, "png", baos);
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        InputStream is = new ByteArrayInputStream(imageInByte);
        baos.close();

        Worksheet sheet = workbook.getWorksheets().get(i);
        sheet.getPictures().add(0, 0, is);

and i got this:

com.aspose.cells.CellsException: Unknown image format
at com.aspose.cells.zalt.a(Unknown Source)
at com.aspose.cells.zst.a(Unknown Source)
at com.aspose.cells.zsr.a(Unknown Source)
at com.aspose.cells.ShapeCollection.a(Unknown Source)
at com.aspose.cells.ShapeCollection.a(Unknown Source)
at com.aspose.cells.PictureCollection.a(Unknown Source)
at com.aspose.cells.PictureCollection.add(Unknown Source)
Caused by: java.lang.IllegalStateException: End of file reached.
at com.aspose.cells.b.a.d.za.a(Unknown Source)
at com.aspose.cells.b.a.d.za.n(Unknown Source)
at com.aspose.cells.a.d.zcd.h(Unknown Source)
at com.aspose.cells.a.d.zcd.j(Unknown Source)
… 9 more

Can someone tell me what im doing wrong? thanks in advance!

Vincent

@dyhstarsun

The code snippet you have shared is working fine with Aspose.Cells for Java 18.7. Please share the image file you are trying to add in the worksheet as there can be some problem with that image file so that we can investigate further.

    Workbook workbook = new Workbook();
    BufferedImage image = ImageIO.read(new File("text.png"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write( image, "png", baos);
    baos.flush();
    byte[] imageInByte = baos.toByteArray();
    InputStream is = new ByteArrayInputStream(imageInByte);
    baos.close();
    Worksheet sheet = workbook.getWorksheets().get(0);
    sheet.getPictures().add(0, 0, is);
    workbook.save("ImageSheet.xlsx");

@ahsaniqbalsidiqui
Thanks for the reply, however i’v found the solution by using sheet.getShapes().addFreeFloatingShape(), i think that the conversion from byte[] to ByteArrayInputStream causes the problem.

@dyhstarsun,

Thanks for your feedback and using Aspose.Cells. It is good to know your issue is resolved now. Let us know if you encounter any issue, we will be glad to look into it and help you further.