将图像(从 drawable 文件夹)转换为 ByteArray [英] Convert Image (from drawable folder) to ByteArray

查看:21
本文介绍了将图像(从 drawable 文件夹)转换为 ByteArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我的代码被困住了.我正在尝试在我的应用程序中创建一个共享按钮以将一些图像共享给其他应用程序.

So, I'm stuck with smth on my code. I'm trying to create a Share button inside my App to share some images to other Apps.

一个工作的朋友和我分享了他使用的相同代码,他获取图像的字节数组并将其传递给DependencyService,但他已经在ByteArray中有他的图像,在我的情况下,我的图像都存储在Resources中/drawable 文件夹.

A friend from work shared with me the same code he uses, he get the bytearray of a image and pass it to a DependencyService, but he already has his images in ByteArray, in my case, my images are all stored inside Resources/drawable folder.

我们试图做但无法做到的是从 drawable 文件夹中获取图像并将其转换为 ByteArray.

What we tried to do but couldn't was to get an image from drawable folder and convert it to ByteArray.

private void ShareImage(object sender, EventArgs e)
{
    //Convert img to ByteArray


    //ShareWindow
    DependencyService.Get<IShare>().Share("", "", buffer);
}

例如,我如何将位于Resources/drawable"(在 Android 和 iOS 项目中)的名为MyImage1.png"的图像转换为 ByteArray?看起来这是这个按钮唯一缺少的东西.

For example, how would I convert an image called "MyImage1.png" that's inside "Resources/drawable" (on both Android and iOS projects) to ByteArray? Looks like it's the only thing missing for this button to work.

谢谢!

推荐答案

您可以通过 DependencyService 调用这些.

You can call these via a DependencyService.

public byte[] DrawableByNameToByteArray(string fileName)
{
    var context = Application.Context;
    using (var drawable = Xamarin.Forms.Platform.Android.ResourceManager.GetDrawable(context, fileName))
    using (var bitmap = ((BitmapDrawable)drawable).Bitmap)
    {
        var stream = new MemoryStream();
        bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
        bitmap.Recycle();
        return stream.ToArray();
    }
}

iOS

public byte[] iOSBundleResourceByNameToByteArray(string fileName)
{
    using (var image = UIImage.FromFile(fileName))
    using (NSData imageData = image.AsPNG())
    {
        var byteArray = new byte[imageData.Length];
        System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, byteArray, 0, Convert.ToInt32(imageData.Length));
        return byteArray;
    }
}

注意:传递 byte[] 非常低效,流更好,但由于您使用的是本机共享"功能,因此最好使用原始文件.

Note: Passing byte[] around is very inefficient, streams are better, but since you are using a native "sharing" feature, you are best off using the original file.

这篇关于将图像(从 drawable 文件夹)转换为 ByteArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆