【问题标题】:Is there a solution to convert an ImageSource to an Android Bitmap and vice-versa in Xamarin.Forms是否有解决方案将 ImageSource 转换为 Android 位图,反之亦然 Xamarin.Forms
【发布时间】:2019-02-11 13:38:56
【问题描述】:

我目前正在开发一个修改当前位于 PCL 项目中的图片的应用程序。我目前在转换 DataTypes 时遇到问题。

我目前正在尝试弄清楚如何将 ImageSource 转换为位图。我在互联网上阅读了一些答案,但它们似乎对我不起作用。

我使用 DependencyService 调用特定于平台的代码,并将 ImageSource 作为参数传递。

函数签名如下所示:

        public ImageSource BlurImage(ImageSource ImageSource)
        {

            return null;
        }

这个函数应该首先从 ImageSource 创建一个位图,一旦完成所有逻辑,它应该转换回 ImageSource。

谁能解释一下我应该如何将 ImageSource 转换为位图,反之亦然?

提前致谢, 汤姆

【问题讨论】:

  • 你的imageSource、冗长的string或.png之类的文件是什么?
  • @CGPA6.4 imageSource 是一个 ImageSource DateType。在调用平台相关代码之前,我从 PCL 项目中的 Image.Source 中检索到它
  • 您最初是如何创建 ImageSource 的?您应该使用该原始图像,而不是 ImageSource
  • 原始Image作为资源在PCL项目中,使用如下:csharp blurImage.Source = ImageSource.FromResource("Guassian.Assets.Images.Test.JPG"); 这个blurImage在Xaml中使用,源稍后作为参数传递

标签: c# android xamarin bitmap imagesource


【解决方案1】:

您可以使用以下函数将ImageSource 转换为Bitmap

 private async Task<Bitmap> GetImageFromImageSource(ImageSource imageSource, Context context)
    {
        IImageSourceHandler handler;

        if (imageSource is FileImageSource)
        {
            handler = new FileImageSourceHandler();
        }
        else if (imageSource is StreamImageSource)
        {
            handler = new StreamImagesourceHandler(); // sic
        }
        else if (imageSource is UriImageSource)
        {
            handler = new ImageLoaderSourceHandler(); // sic
        }
        else
        {
            throw new NotImplementedException();
        }

        var originalBitmap = await handler.LoadImageAsync(imageSource, context);         

        return originalBitmap;
    }

还有BitmapImageSource 的下一个:

public async Task<ImageSource> GetBytesFromImage(Bitmap bitmap)
 {
    ImageSource imgSource;
    using (var stream = new MemoryStream())
    {
        bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream); // You can change the compression asper your understanding
        imgSource=ImageSource.FromStream(stream);
    }
   return imgSource;
  }

【讨论】:

  • 谢谢您的回答。明天我会试试这个,可能会将其标记为已解决
  • 当然没问题,如果有问题请告诉我
  • 它确实有效,更多信息在这里:medium.com/@hakimgulamali88/…
猜你喜欢
  • 2012-07-01
  • 2013-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多