问题描述
我有一个简单的问题,但到目前为止我还没有找到答案:如何在 C# WinRT/WinMD 项目中调整 jpeg 图像的大小并将其另存为新的 jpeg?
I've got simple question, but so far I've found no answer: how to resize jpeg image in C# WinRT/WinMD project and save it as new jpeg?
我正在开发 Windows 8 Metro 应用程序,用于从某个站点下载每日图像并将其显示在动态磁贴上.问题是图像必须小于 1024x1024 且小于 200kB,否则它不会显示在图块上:http://msdn.microsoft.com/en-us/library/windows/apps/hh465403.aspx
I'm developing Windows 8 Metro application for downloading daily image form certain site and displaying it on a Live Tile. The problem is the image must be smaller than 1024x1024 and smaller than 200kB, otherwise it won't show on the tile: http://msdn.microsoft.com/en-us/library/windows/apps/hh465403.aspx
如果我有更大的图像,如何调整它的大小以适合动态磁贴?我正在考虑简单的调整大小,如宽度/2 和高度/2,同时保持纵横比.
If I got larger image, how to resize it to be fit for the Live Tile? I'm thinking just about simple resize like width/2 and height/2 with keeping the aspect ration.
这里的具体要求是代码必须作为 Windows 运行时组件运行,因此 WriteableBitmapEx 库在这里不起作用 - 它仅适用于常规 WinRT 项目.甚至还有一个将 WriteableBitmapEx 作为 winmd 项目的分支,但还远远没有准备好.
The specific requirement here is that the code must run as Windows Runtime Component, so WriteableBitmapEx library won't work here - it's only available for regular WinRT projects. There is even a branch for WriteableBitmapEx as winmd project, but it's far from ready.
推荐答案
如何缩放和裁剪的示例取自 这里:
Example of how to scale and crop taken from here:
async private void BitmapTransformTest()
{
// hard coded image location
string filePath = "C:\Users\Public\Pictures\Sample Pictures\fantasy-dragons-wallpaper.jpg";
StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
if (file == null)
return;
// create a stream from the file and decode the image
var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
// create a new stream and encoder for the new image
InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
BitmapEncoder enc = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder);
// convert the entire bitmap to a 100px by 100px bitmap
enc.BitmapTransform.ScaledHeight = 100;
enc.BitmapTransform.ScaledWidth = 100;
BitmapBounds bounds = new BitmapBounds();
bounds.Height = 50;
bounds.Width = 50;
bounds.X = 50;
bounds.Y = 50;
enc.BitmapTransform.Bounds = bounds;
// write out to the stream
try
{
await enc.FlushAsync();
}
catch (Exception ex)
{
string s = ex.ToString();
}
// render the stream to the screen
BitmapImage bImg = new BitmapImage();
bImg.SetSource(ras);
img.Source = bImg; // image element in xaml
}
这篇关于如何在 C# WinRT/winmd 中调整图像大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!