将Android.Graphics.Bitmap转换为Image

时间:2015-10-13 23:01:35

标签: android bitmap xamarin

我正在尝试获取视图的屏幕截图,如下所示。我正在获取Bitmap,我需要将其转换为Image以添加到PDF生成器中。

using (var screenshot = Bitmap.CreateBitmap(200, 100,Bitmap.Config.Argb8888))
{
    var canvas = new Canvas(screenshot);
    rootView.Draw(canvas);

    using (var screenshotOutputStream = new FileStream(screenshotPath,System.IO.FileMode.Create))
    {
        screenshot.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 90, screenshotOutputStream);
        screenshotOutputStream.Flush();
        screenshotOutputStream.Close();
    }
}

我的问题是如何将Android.Graphics.Bitmap -->screenshot转换为Image

我想用来自BitMap的Image本身替换url。

String imageUrl = "myURL";
Image image = Image.GetInstance (new Uri (imageUrl));
document.Add(image);

2 个答案:

答案 0 :(得分:5)

您可以使用此方法:

public Bitmap getScreenshotBmp() {


    FileOutputStream fileOutputStream = null;

    File path = Environment
            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

    String uniqueID = UUID.randomUUID().toString();

    File file = new File(path, uniqueID + ".jpg");
    try {
        fileOutputStream = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    screenshot.compress(Bitmap.CompressFormat.JPEG, 30, fileOutputStream);

    try {
        fileOutputStream.flush();
        fileOutputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return screenshot;
 }

答案 1 :(得分:2)

Bitmap bm = BitmapFactory.DecodeFile (path);
MemoryStream stream = new MemoryStream ();
bm.Compress (Bitmap.CompressFormat.Jpeg, 100, stream);
Image img = Image.FromArray (stream.ToArray());