如何通过字节数组将图像缩放到一半大小?

时间:2014-01-05 05:06:46

标签: image-processing windows-runtime bytearray transform writeablebitmap

我找到了许多关于如何在Windows窗体中扩展图像的示例,但在这种情况下,我在Windows应用商店应用程序中使用了一个字节数组。这是我正在使用的代码片段。

// Now that you have the raw bytes, create a Image Decoder
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);

// Get the first frame from the decoder because we are picking an image
BitmapFrame frame = await decoder.GetFrameAsync(0);

// Convert the frame into pixels
PixelDataProvider pixelProvider = await frame.GetPixelDataAsync();

// Convert pixels into byte array
srcPixels = pixelProvider.DetachPixelData();
wid = (int)frame.PixelWidth;
hgt =(int)frame.PixelHeight;

// Create an in memory WriteableBitmap of the same size
bitmap = new WriteableBitmap(wid, hgt);
Stream pixelStream = bitmap.PixelBuffer.AsStream();
pixelStream.Seek(0, SeekOrigin.Begin);

// Push the pixels from the original file into the in-memory bitmap
pixelStream.Write(srcPixels, 0, (int)srcPixels.Length);
bitmap.Invalidate();

在这种情况下,它只是创建流的副本。我不知道如何操作字节数组以将其减少到半宽和高度。

1 个答案:

答案 0 :(得分:0)

如果您查看GetPixelDataAsync BitmapTransform,可以看到它有一个重载,允许您指定在操作期间应用的// decode a frame (as you do now) BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream); BitmapFrame frame = await decoder.GetFrameAsync(0); // calculate required scaled size uint newWidth = frame.PixelWidth / 2; uint newHeight = frame.PixelHeight / 2; // convert (and resize) the frame into pixels PixelDataProvider pixelProvider = await frame.GetPixelDataAsync( BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, new BitmapTransform() { ScaledWidth = newWidth, ScaledHeight = newHeight}, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

所以你可以在你的示例代码中执行此操作,如下所示:

DetachPixelData

现在,您可以像原始代码一样调用srcPixels = pixelProvider.DetachPixelData(); // create an in memory WriteableBitmap of the scaled size bitmap = new WriteableBitmap(newWidth, newHeight); Stream pixelStream = bitmap.PixelBuffer.AsStream(); pixelStream.Seek(0, SeekOrigin.Begin); // push the pixels from the original file into the in-memory bitmap pixelStream.Write(srcPixels, 0, (int)srcPixels.Length); bitmap.Invalidate(); ,但这会为您提供已调整大小的图片,而不是全尺寸图片。

{{1}}