UWP:如何调整图像大小

时间:2016-03-15 10:45:09

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

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

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只包含零,尽管已写入正确的字节数。

2 个答案:

答案 0 :(得分:10)

只需从此

替换您的行
uint x =  await resizedStream.WriteAsync(outBuffer.AsBuffer());

到此代码:

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

答案 1 :(得分:0)

我上周偶然发现了同样的问题,最终找到了一个类似的解决方案。

private async Task<StorageFile> RescaleImage(StorageFile sourceFile, StorageFile resizedImageFile,uint width,uint height)
{
    var imageStream = await sourceFile.OpenReadAsync();
    var decoder = await BitmapDecoder.CreateAsync(imageStream);
    using (var resizedStream = await resizedImageFile.OpenAsync(FileAccessMode.ReadWrite))
    {   
        var encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
        encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;
        encoder.BitmapTransform.ScaledWidth = width;
        encoder.BitmapTransform.ScaledHeight = height;
        await encoder.FlushAsync();
    }
    return resizedImageFile;
}