Reputation: 11
I am developing an application in C#/UWP that opens images, modifies them and saves them. The application supports multiple file extensions and I have an issue with all file formats. In this case, I use PNG and JPG test images as an exemple.
I am using the BitmapDecoder class in an UWP app to open images in using the following code.
using (IRandomAccessStreamWithContentType imageFileStream = await imageStorageFile.OpenReadAsync())
{
BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(imageFileStream);
PixelDataProvider pixelDataProvider = await bitmapDecoder.GetPixelDataAsync();
pixelData = pixelDataProvider.DetachPixelData();
encoderGuid = bitmapDecoder.DecoderInformation.CodecId;
}
The encoder returns Guid’s like ‘9456a480-e88b-43ea-9e73-0b2d9b71b1ca’ for a PNG test image, and I suspected that it was directly usable in the Encryptor class I use to write. My program modifies the image, and saves them to another image in the same format for which I use the BitmapEncoder.
using (IRandomAccessStream imageFileStream = await imageStorageFile.OpenAsync(FileAccessMode.ReadWrite))
{
BitmapEncoder bitmapEncoder = await BitmapEncoder.CreateAsync(encoderGuid, imageFileStream);
bitmapEncoder.SetPixelData(bitmapPixelFormat, bitmapAlphaMode, pixelWidth, pixelHeight, dpiX, dpiY, pixelData);
await bitmapEncoder.FlushAsync();
}
In this step, I get an error 'Specified cast is not valid' in the BitmapEncoder.CreateAsync method because it does not accept the Guid earlier created by the decoder.
The Guid does not corresponds to any of the static encoder id’s.
BitmapEncoder.PngEncoderId
BitmapEncoder.JpegEncoderId
BitmapEncoder.JpegXREncoderId
BitmapEncoder.TiffEncoderId
BitmapEncoder.BmpEncoderId
BitmapEncoder.GifEncoderId
I can enter these static Guid’s without having the “Specified cast is not valid” exception. Altough, when I used the BitmapEncoder.PngEncoderId, the program saved a png image with only pixel noice.
Any idea what I am doing wrong please? Any help is welcome. Thank you!
Upvotes: 1
Views: 267
Reputation: 8591
@Jeroen Mostert was on the right way. You could manually convert it.
For example,
if (bitmapDecoder.DecoderInformation.CodecId == BitmapDecoder.BmpDecoderId)
{
encoderGuid = BitmapEncoder.BmpEncoderId;
}
else if (bitmapDecoder.DecoderInformation.CodecId == BitmapDecoder.GifDecoderId)
{
encoderGuid = BitmapEncoder.GifEncoderId;
}
else if (bitmapDecoder.DecoderInformation.CodecId == BitmapDecoder.JpegDecoderId)
{
encoderGuid = BitmapEncoder.JpegEncoderId;
}
else if (bitmapDecoder.DecoderInformation.CodecId == BitmapDecoder.JpegXRDecoderId)
{
encoderGuid = BitmapEncoder.JpegXREncoderId;
}
else if (bitmapDecoder.DecoderInformation.CodecId == BitmapDecoder.PngDecoderId)
{
encoderGuid = BitmapEncoder.PngEncoderId;
}
else if (bitmapDecoder.DecoderInformation.CodecId == BitmapDecoder.TiffDecoderId)
{
encoderGuid = BitmapEncoder.TiffEncoderId;
}
else
{
throw new NotSupportedException("unknown Codec");
}
Upvotes: 1