Free Support Forum - aspose.com

Imaging - Unable to cast object of type

Hi,

We implemented a validation to prevent users from uploading PNG files with transparency using this code snippet:

using (PngImage image = (PngImage)Aspose.Imaging.Image.Load(filePath))
{
float opacity = image.ImageOpacity;
if (opacity != 1)
{
errors.Add(ValidationMessage.Keys.DocumentationInfoModelKeys.IMAGE_WITH_TRANSPARENCY);
}
}

But, we are having issues with some PNG files. Here is one file: Upload Error.jpg (10.0 KB)

It’s throwing the following exception:
Unable to cast object of type ‘Aspose.Imaging.FileFormats.Jpeg.JpegImage’ to type ‘Aspose.Imaging.FileFormats.Png.PngImage’.

How can we prevent this from happening? What else are we missing? Should we include some additional validations?
Please let us know and include some code snippets. Thanks!

@jimmy.rojas,

I have observed the issue shared by you and it is problem related to your implementation. You are trying to load a JPG using PngImage class, which is wrong. You may try using following sample code.

        using (Image img = Aspose.Imaging.Image.Load(filePath))
        {
            var fileFormat = img.FileFormat;
            if(fileFormat==FileFormat.Jpeg)
            {
                JpegImage image = (JpegImage)img;
                float opacity = image.ImageOpacity;
                if (opacity != 1)
                {
                    errors.Add(ValidationMessage.Keys.DocumentationInfoModelKeys.IMAGE_WITH_TRANSPARENCY);
                }


            }
            else
            {
                PngImage image = (PngImage)img;

                float opacity = image.ImageOpacity;
                if (opacity != 1)
                {
                    errors.Add(ValidationMessage.Keys.DocumentationInfoModelKeys.IMAGE_WITH_TRANSPARENCY);
                }

            }
        }