我正在开发一个例程来缩放一些位图图像,使其成为我的Window-8应用程序的磁贴通知的一部分
磁贴图像必须小于200kb且尺寸小于1024x1024像素。我可以使用缩放例程根据需要调整源图像的大小,以满足1024x1024像素的尺寸限制。
如何更改源映像以保证满足大小限制?
我的第一个尝试是继续缩小图像,直到它清除大小阈值,并使用isTooBig = destFileStream.Size > MaxBytes来确定大小。但是,下面的代码导致了无限循环。如何可靠地测量目标文件的大小?
bool isTooBig = true;
int count = 0;
while (isTooBig)
{
// create a stream from the file and decode the image
using (var sourceFileStream = await sourceFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
using (var destFileStream = await destFile.OpenAsync(FileAccessMode.ReadWrite))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceFileStream);
BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(destFileStream, decoder);
double h = decoder.OrientedPixelHeight;
double w = decoder.OrientedPixelWidth;
if (h > baselinesize || w > baselinesize)
{
uint scaledHeight, scaledWidth;
if (h >= w)
{
scaledHeight = (uint)baselinesize;
scaledWidth = (uint)((double)baselinesize * (w / h));
}
else
{
scaledWidth = (uint)baselinesize;
scaledHeight = (uint)((double)baselinesize * (h / w));
}
//Scale the bitmap to fit
enc.BitmapTransform.ScaledHeight = scaledHeight;
enc.BitmapTransform.ScaledWidth = scaledWidth;
}
// write out to the stream
await enc.FlushAsync();
await destFileStream.FlushAsync();
isTooBig = destFileStream.Size > MaxBytes;
baselinesize *= .90d * ((double)MaxBytes / (double)destFileStream.Size);
}
}发布于 2012-10-13 07:26:41
你能不能不用宽度x高度x colourDepth (其中colourDepth是字节,所以是32bit=4bytes)来计算它。假设你保持宽高比,所以你只需要缩小宽/高,直到你发现它小于200KB。
这假设输出是位图,因此是未压缩的。
发布于 2012-10-13 13:57:35
考虑到平铺大小,无论是正方形平铺的150x150,还是宽平铺的310x150,你应该能够将图像缩小到合适的大小,并且使用jpeg压缩,你几乎可以保证在200k以下。将压缩质量设置为80左右。它将为您提供良好的压缩比,同时保持良好的图像质量。
https://stackoverflow.com/questions/12868303
复制相似问题