2011-06-25 243 views
5

如何將位圖對象作爲映像保存到Amazon S3?使用C#將文件添加到Amazon S3上的存儲桶

我已經有了一切設置,但是我的有限的C sharp正在阻止我完成這項工作。

// I have a bitmap iamge 
Bitmap image = new Bitmap(width, height); 

// Rather than this 
image.save(file_path); 

// I'd like to use S3 
S3 test = new S3(); 
test.WritingAnObject("images", "testing2.png", image); 

// Here is the relevant part of write to S3 function 
PutObjectRequest titledRequest = new PutObjectRequest(); 
titledRequest.WithMetaData("title", "the title") 
      .WithContentBody("this object has a title") 
      .WithBucketName(bucketName) 
      .WithKey(keyName); 

正如你所看到的S3函數只能取一個字符串並將其保存爲文件的主體。

我該如何寫這樣的方式,它將允許我傳入位圖對象並將其保存爲圖像?也許作爲一個流?或者作爲一個字節數組?

我很感激任何幫助。

+0

嗯......你的圖像保存到文件,將文件轉換爲十六進制字符串並傳遞字符串?我對s3一無所知,但我認爲這可以提供幫助。 – Vercas

+0

我不希望首先將圖像保存到文件的開銷。我相信它可以在圖像仍在記憶中時完成。 – Abs

+0

然後將其保存到內存流中。 – Vercas

回答

11

你會使用WithInputStreamWithFilePath。例如在一個新的圖像保存到S3:

using (var memoryStream = new MemoryStream()) 
{ 
    using(var yourBitmap = new Bitmap()) 
    { 
     //Do whatever with bitmap here. 
     yourBitmap.Save(memoryStream, ImageFormat.Jpeg); //Save it as a JPEG to memory stream. Change the ImageFormat if you want to save it as something else, such as PNG. 
     PutObjectRequest titledRequest = new PutObjectRequest(); 
     titledRequest.WithMetaData("title", "the title") 
      .WithInputStream(memoryStream) //Add file here. 
      .WithBucketName(bucketName) 
      .WithKey(keyName); 
    } 
} 
+0

好吧,這是有道理的,我將如何將位圖對象轉換爲內存流?道歉,如果這是一個簡單的問題,但我是一個新手談到C#。 – Abs

+1

@Abs:我更新了代碼示例以包含將位圖保存到MemoryStream的示例。 – vcsjones

+0

它的工作。但是我必須在'WithKey(keyName)'之後將調用放到'.WithInputStream(memoryStream)'中。我現在只需要解決一個無法訪問封閉流,當我嘗試這樣做:'使用(S3Response responseWithMetadata = client.PutObject(標題請求))' - 任何想法? – Abs

2

設置你的請求對象的InputStream的屬性:

titledRequest.InputStream = image; 
相關問題