Search code examples
c#imagesharpsixlabors.imagesharp

Unable to read PPI of PNG image using ImageSharp Library in C#


I have an image which is 386x246px - and 150ppi (as shown in Photoshop below):

Photoshop metadata

I'm using the ImageSharp library - and the following code to read it:

uploadedFileName = Path.GetFileNameWithoutExtension(files[0]);
string base64Image = files[0];
originalImageData = ConvertBase64ToByteArray(base64Image);
    
var imageData = ConvertBase64ToByteArray(base64Image);

using (var image = Image.Load(imageData)) 
{
    originalImageWidth = image.Width;
    originalImageHeight = image.Height;
            
    // Retrieve PPI from image metadata
    var horizontalPPI = image.Metadata.HorizontalResolution;
    var verticalPPI = image.Metadata.VerticalResolution;

    Console.WriteLine($"Image Width: {originalImageWidth}");
    Console.WriteLine($"Image Height: {originalImageHeight}");
    Console.WriteLine($"Horizontal DPI: {horizontalDPI}");
    Console.WriteLine($"Vertical DPI: {verticalDPI}");
}

result shows in console:

Image Width: 386

Image Height: 246

Horizontal PPI: 5905

Vertical PPI: 5905

Loading the image back into Photoshop, it again shows the correct dimensions and a ppi of 150. Is there any way to read the correct ppi from the image data in ImageSharp? Additionally - as DPI and PPI are different, is it possible to read DPI from the ImageSharp library?


Solution

  • The PPI output you're seeing is likely in dots per meter rather than pixels per inch (PPI). If you convert 5905 dots per meter to PPI, you get approx. 150 PPI.

    To confirm, you can check the ResolutionUnits property in the ImageMetadata object, with the code you mentioned:

    ImageMetadata metadata = image.Metadata;
    PixelResolutionUnit resolutionUnit = metadata.ResolutionUnits;
    Console.WriteLine($"Resolution Unit: {resolutionUnit}");