Xamarin 窗体从映像控件获取字节数组



在我的应用程序中,我让用户选择一个图像(任何大小(。 然后,应用程序会将其加载到图像控件,根据需要调整其大小,并将其显示在屏幕上。

我现在从首选项中获取所有保存/加载功能都可以正常工作,因为我使用 Xamarin Forms 插件.FilePicker 并从中获取字节数组以保存到我的首选项中。

我面临的挑战是,如果使用从他们的设备中图片大图像,则图像的大版本是上传到FilePicker插件的内容,并且字节数组太大而无法保存。 (我收到错误"状态管理器设置值的大小已超过限制。

因此,我想做的是获取图像控件的内容,这些内容已调整为可管理的大小,将其转换为字节数组,然后将其保存在我的首选项中。

知道如何将图像控件的内容转换为字节数组,以便我可以在 JSON 中序列化它并将其保存到我的首选项中吗? 下面是从文件选取器保存字节数组的代码。

private async void btnChooseFile_Clicked(object sender, System.EventArgs e)
{
try
{
FileData fileData = await CrossFilePicker.Current.PickFile();
if (fileData == null)
return; // user canceled file picking
//lblFilePath.Text = fileData.FileName;
imgIcon.Source = ImageSource.FromStream(() => fileData.GetStream());
// THIS IS THE LINE OF CODE I NEED TO CHANGE TO IT SAVES THE 
// BYTE ARRAY OF THE SMALLER IMAGE AS DISPLAYED BY THE 
// IMAGE CONTROL INSTEAD OF THE FULL SIZE FILE THE USER
// SELECTED 
ViewModelObjects.AppSettings.KioskIcon = fileData.DataArray;
}
catch (Exception ex)
{
System.Console.WriteLine("Exception choosing file: " + ex.ToString());
}
}

您可以调整图像大小的大小,以便将值分配给图像控件:

#if __IOS__
public static byte[] ResizeImageIOS(byte[] imageData, float width, float height)
{
UIImage originalImage = ImageFromByteArray(imageData);
UIImageOrientation orientation = originalImage.Orientation;
//create a 24bit RGB image
using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
(int)width, (int)height, 8,
4 * (int)width, CGColorSpace.CreateDeviceRGB(),
CGImageAlphaInfo.PremultipliedFirst))
{
RectangleF imageRect = new RectangleF(0, 0, width, height);
// draw the image
context.DrawImage(imageRect, originalImage.CGImage);
UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, orientation);
// save the image as a jpeg
return resizedImage.AsJPEG().ToArray();
}
}

#if __ANDROID__
public static byte[] ResizeImageAndroid (byte[] imageData, float width, float height)
{
// Load the bitmap
Bitmap originalImage = BitmapFactory.DecodeByteArray (imageData, 0, imageData.Length);
Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int)width, (int)height, false);
using (MemoryStream ms = new MemoryStream())
{
resizedImage.Compress (Bitmap.CompressFormat.Jpeg, 100, ms);
return ms.ToArray ();
}
}

你可以参考图像调整器

最新更新