c# - UWP : How to resize an Image

标签 c# image-processing win-universal-app

我有一个 JPEG 图像存储在我想要调整大小的 Byte[] 中。这是我的代码:

public async Task<byte[]> ResizeImage(byte[] imageData, int reqWidth, int reqHeight, int quality)
{

    var memStream = new MemoryStream(imageData);

    IRandomAccessStream imageStream = memStream.AsRandomAccessStream();
    var decoder = await BitmapDecoder.CreateAsync(imageStream);
    if (decoder.PixelHeight > reqHeight || decoder.PixelWidth > reqWidth)
    {
        using (imageStream)
        {
            var resizedStream = new InMemoryRandomAccessStream();

            BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
            double widthRatio = (double) reqWidth/decoder.PixelWidth;
            double heightRatio = (double) reqHeight/decoder.PixelHeight;

            double scaleRatio = Math.Min(widthRatio, heightRatio);

            if (reqWidth == 0)
                scaleRatio = heightRatio;

            if (reqHeight == 0)
                scaleRatio = widthRatio;

            uint aspectHeight = (uint) Math.Floor(decoder.PixelHeight*scaleRatio);
            uint aspectWidth = (uint) Math.Floor(decoder.PixelWidth*scaleRatio);

            encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;

            encoder.BitmapTransform.ScaledHeight = aspectHeight;
            encoder.BitmapTransform.ScaledWidth = aspectWidth;

            await encoder.FlushAsync();
            resizedStream.Seek(0);
            var outBuffer = new byte[resizedStream.Size];
            uint x =  await resizedStream.WriteAsync(outBuffer.AsBuffer());
            return outBuffer;
        }
    }
    return imageData;
}

问题是尽管写入了正确数量的字节,但 outBuffer 只包含零。

最佳答案

只需从这里替换你的行

uint x =  await resizedStream.WriteAsync(outBuffer.AsBuffer());

此代码:

await resizedStream.ReadAsync(outBuffer.AsBuffer(), (uint)resizedStream.Size, InputStreamOptions.None);

关于c# - UWP : How to resize an Image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36009021/

相关文章:

c# - HTML5 视频 - 从 SQL 文件流流式传输

c# - 需要一个会失败的场景 Array.ConstrainedCopy()

java - 在java和eclipse上将图像从.bmp转换为jpeg2000错误

c# - ScrollViewer 中的图像导致内存泄漏

c# - MonoTouch 中的 ViewForZoomingInScrollView

c# - 我现在如何在 Irony 中使用 AST?

c++ - 以下图像处理功能如何工作?

python - 使用 python 从图像中提取对象

windows-phone-8 - 通用 Windows Phone 8.1 应用程序中的 App.Current.Host 去哪儿了?

c# - Raspberry Pi 3 - Windows 10 IOT Core 上 C# 中的 USB 到串行通信