I need to allow my app to accept any image format and then convert the image into a .jpeg file. I am using Magick.NET to complete the conversion.
The Magick.NET version is: Magick.NET-Q8-AnyCPU 13.6.0.
My implementation looks like this:
var memStream = new MemoryStream();
if (contentType != "image/jpeg")
{
var convertedImageFile = new MagickImage(imageFile);
convertedImageFile.Format = MagickFormat.Jpeg;
convertedImageFile.Write(memStream);
memStream.Position = 0;
}
var blobClient = containerClient.GetBlobClient(imageFileName);
var headers = new BlobHttpHeaders
{
ContentType = "image/jpeg"
};
await blobClient.UploadAsync(memStream, headers, metadata);
My tests look like this:
// Arrange
var fileName = "{filePath}/imageTestFile.png";
var containerClient = blobServiceClient.GetBlobContainerClient();
// Act
/* Make request to endpoint and pass the `.png` test file. */
// Assert
var blobClient = containerClient.GetBlobClient(imageId);
var blobClientFile = await blobClient.OpenReadAsync();
var file = File.OpenRead(fileName);
Assert.Equal(blobClientFile, file);
I need to write a test that checks that the file stored in the BlobClient is the same file that I passed along with my request but as a .jpeg rather than a .png.
My current tests returns:
Assert.Equal() Failure: Values differ
Expected: 11417
Actual: 33383
How can I write a test that checks the original .png file has been sent as a request, converted to a .jpg and then stored successfully in the BlobClient?
Summary:
Reason:
Any image converted into a JPEG will never produce exactly the same image. Either in size, or in appearance. You can't write any meaningful test for this.
It's important to understand that JPEG files are a lossy compression method. This means that they deliberately throw away some of the image detail, as part of the compression algorithm.
In fact even if you take an existing JPEG, load it into memory as a bitmap, and then re-save it as a JPEG, it will still be different.
https://en.wikipedia.org/wiki/JPEG
(NB there are exceptions to the above for some niche types of JPEG)
There's no perfect format:
As an aside, also be sure you're using JPEG for the right purpose. JPEG is only of benefit to photography or similar artwork. The compression method is optimised for patterns with colour gradations, and doesn't work well with sharp contrast e.g. line drawings. Sharp lines saved as a JPEG will look poor and actually don't compress very well.
So if you have images that are diagrams, or line drawings, or cell animation, then consider retaining them as PNG.