gpt4 book ai didi

xamarin - 将 HEIC 图像转换为 Jpg 并上传到 Xamarin iOS 中的服务器

转载 作者:行者123 更新时间:2023-12-05 02:14:07 25 4
gpt4 key购买 nike

我正在尝试使用依赖服务将 HEIC 图像从下面的代码转换为 Jpg,并尝试使用图像显示并上传到 Web API。但是两者都不起作用,这是将 HEIC 转换为 Jpg 的正确方法吗?如果没有,请建议我如何实现这一目标。

依赖服务方法:

public byte[] GetJpgFromHEIC(string path)
{
byte[] imageAsBytes = File.ReadAllBytes(path);
UIImage images = new UIImage(NSData.FromArray(imageAsBytes));
byte[] bytes = images.AsJPEG().ToArray();
// Stream imgStream = new MemoryStream(bytes);

return bytes;
}

在显示图片的 Xaml 代码中:

Image image = new Image(){};
byte[] bytes = DependencyService.Get<ICommonHelper>
().GetJpgFromHEIC(fileData.FileName);
image.Source = ImageSource.FromStream(() => new MemoryStream(bytes));

将代码上传到 Web API:在 StreamContent 和 ByteArrayContent 中尝试作为 HttpContent,如下所示

   HttpResponseMessage response = null;

string filename = data.FileName; // here data object is a FileData, picked from using FilePicker.

byte[] fileBytes = DependencyService.Get<ICommonHelper>().GetJpgFromHEIC(data.FilePath);

HttpContent fileContent = new ByteArrayContent(fileBytes);

// Stream fileStream = new MemoryStream(fileBytes);
// HttpContent fileContent = new StreamContent(fileStream);

fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name =
"file", FileName = data.FileName };
fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent);
response = await client.PostAsync(uri, formData);
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(@" Upload CommentsAttachments SUCCESS>> " + response.Content.ToString());
}
}

请告诉我我做错了什么,如何实现以及这种转换和上传的可能方法。

谢谢,

最佳答案

像这样的东西适用于 HEIC 路径/文件(或任何有效的 iOS 支持的图像格式)。我正在使用示例 autumn_1440x960.heic

using (var image = UIImage.FromFile(path))
using (var jpg = image.AsJPEG(0.5f))
using (var stream = jpg.AsStream())
{
// do something with your stream, just saving it to the cache directory as an example...

using (var cache = NSFileManager.DefaultManager.GetUrl(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.All, null, true, out var nsError))
using (var fileStream = new FileStream(Path.Combine(cache.Path, "cache.jpg"), FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
imageView1.Image = UIImage.FromFile(Path.Combine(cache.Path, "cache.jpg"));
}
}

仅供引用:复制 byte[] 是非常低效的,您可能只想将原始流传回并使用它来填充要发布的表单内容,只需让您处理它,否则您将泄漏 native 分配...

关于xamarin - 将 HEIC 图像转换为 Jpg 并上传到 Xamarin iOS 中的服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54103811/

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