gpt4 book ai didi

c# - UWP:如何降低所选图像的质量?

转载 作者:太空宇宙 更新时间:2023-11-03 19:02:11 26 4
gpt4 key购买 nike

我有代码允许用户使用文件选择器选择图像,我将图像转换为字节数组,以便可以序列化。查看图像集时,如果我有太多图像,应用程序会崩溃并且无法加载。当我使用 visual studio 进行调试时,它运行良好但需要很长时间才能加载图像。我相信它会超时,因为它需要很长时间才能加载。拿到存储文件后。如何降低 BitmapImage 的质量,以便在序列化时加载时间不长?

 private async void AddPic_OnClick(object sender, RoutedEventArgs e)
{
ImagePath = string.Empty;
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

openPicker.FileTypeFilter.Clear();
openPicker.FileTypeFilter.Add(".bmp");
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");

// Launch file open picker and caller app is suspended and may be terminated
var file = await openPicker.PickSingleFileAsync();

if (file != null)
{
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
var image = new BitmapImage();
image.SetSource(stream);
xamlimg.Source = image;
_myClass.ImageBytes = await App.DataModel.GetBytesAsync(file);

}
}

其他类的详细信息:

public BitmapImage Image
{
get
{
if (ImageBytes == null)
return null;
if (_Image == null)
_Image = new BitmapImage();
using (var stream = new InMemoryRandomAccessStream())
{
stream.WriteAsync(ImageBytes.AsBuffer()).Completed = (i, j) =>
{
stream.Seek(0);
_Image.SetSource(stream);
};
}
return _Image;
}
}

[JsonProperty]
public byte[] ImageBytes { get; set; }

public async Task<byte[]> GetBytesAsync(StorageFile file)
{
byte[] fileBytes = null;
if (file == null) return null;
using (var stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint) stream.Size);
reader.ReadBytes(fileBytes);
}
}
return fileBytes;
}

最佳答案

您可以对其进行解码并将其缩小。因此,一旦您从文件选择器中获得结果,您就可以:

using (IRandomAccessStream fileStream = await result.OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
using (var encoderStream = new InMemoryRandomAccessStream())
{
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(encoderStream, decoder);
var newHeight = decoder.PixelHeight / 2;
var newWidth = decoder.PixelWidth / 2;
encoder.BitmapTransform.ScaledHeight = newHeight;
encoder.BitmapTransform.ScaledWidth = newWidth;

await encoder.FlushAsync();

byte[] pixels = new byte[newWidth * newHeight * 4];

await encoderStream.ReadAsync(pixels.AsBuffer(), (uint)pixels.Length, InputStreamOptions.None);
}

为了序列化,字节数组像素应该更小,但图像质量会更差。

关于c# - UWP:如何降低所选图像的质量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34362217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com