如何将位图图像大小调整为 <200 KB 并满足平铺限制 (WinRT)

2023-12-04

我正在开发一个例程来缩放一些位图图像,使其成为我的 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);
            }
        }

你能不能用宽度x高度x颜色深度来计算它(其中颜色深度以字节为单位,所以32位= 4字节)。假设您保持纵横比,因此您只需缩小宽度/高度,直到发现它小于 200KB。

这假设输出是位图,因此未压缩。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将位图图像大小调整为 <200 KB 并满足平铺限制 (WinRT) 的相关文章

随机推荐