2015-10-13 232 views
3

我試圖按如下方式獲取視圖的屏幕截圖。我得到的位圖,我需要將其轉換爲圖像添加到PDF生成器。將Android.Graphics.Bitmap轉換爲圖像

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); 
+0

System.Drawing.Image對象不Xamarin的Android支持。 – Jason

+0

請看我的三行代碼 - 只是添加到我的問題 - 這是在'Xamarin.Android'工作。你有任何建議獲取視圖的截圖並將其分配給圖像生成pdf。 – hotspring

+0

這是一個Android.Media.Image。對不起,我誤解你在問什麼。 – Jason

回答

3

您可以使用此方法:

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; 
} 
+0

嗨Udi,在我看來,它仍然是'位圖'?我沒有看到代碼中的'圖像'轉換?我錯過了什麼嗎? – hotspring

+1

此行假設要這樣做: screenshot.compress(Bitmap.CompressFormat.JPEG,30,fileOutputStream); –

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