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

Free Support Forum - aspose.com

Fit image in cell without distorting the image ratio

Hello, as the title indicates I am having trouble inserting an Image into a Cell without distorting its ratio. I am currently setting fixed width and height size but the ideal would be to set them based on the cell and without distorting the image.

Our implementation is in Java and this is part of the code:

....
// Export Image
Image image = generateImage(A_RANDOM_URL);
row.getCells().get_Item(i).getParagraphs().add(image);
....

private Image generateImage(String urlToReq) throws MyException {
    Image image1 = new Image();
    image1.setFixHeight(60);
    image1.setFixWidth(60);

    try {
        URL url = new URL(urlToReq);
        final InputStream input = url.openStream();
        BufferedImage bufferinput = ImageIO.read(input);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferinput, "jpg", os);
        InputStream is = new ByteArrayInputStream(os.toByteArray());
        image1.setImageStream(is);
    } catch (IOException e) {
       ...
    }
    return image1;
}

For example, when i add an image that depicts a circle and the cells of the PDF are a lot and contain plenty of text (assume that the other cells contain only text), then the width of the image-cell decreases and the circle in the image looks distorted.

I found this blog post but it wasn’t of much help since it uses Aspose.word cells.

Any ideas?

@Enter,

In order to maintain the aspect ratio on creating another image with different size, this is a simple bit of math: (width / height) = (new_width / new_height)

If you know one of the ‘new’ sizes, the other can be found via multiplication:
new_height * (width / height) = new_width

Furthermore, the Cell instance, has a Width property which can help you to set the image size. If all above information does not help, then please send all details of the scenario, including source documents and the complete code. We will investigate your scenario in our environment, and share our findings with you.

@imran.rafique

Thanks for the quick response.

I understand what you are saying but I am still trying to deal with the following issue.
Since the default width of the Cell is 0, I manually set the width to 60 in order to be able to calculate the width/height of the image.

However when a row contains a lot of columns, the width of the cell is forced to be < 60 and the circle that i previously mentioned takes an egg-like shape.

So a 100 x 100 image that gets converted to a 60 x 60 image (in order to fit in the cell) is now forced to be a 50 x 60 image due to multiple columns in a row.

@Enter,

Please send us your source PDF, the complete code and a snapshot of expected view of the image in the table. We will investigate your scenario and share our findings with you.