使用C#将文件添加到Amazon S3存储桶

7

我该如何将位图对象保存为Amazon S3中的图像?

我已经做好了一切准备,但我的C#编程水平有限,无法完成此操作。

// 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函数只能接受字符串并将其保存为文件的正文。

我该如何编写代码,以便允许我传递位图对象并将其保存为图像?也许是作为流?还是作为字节数组?

非常感谢您的帮助。


嗯...将您的图像保存到文件中,将该文件转换为十六进制字符串并传递该字符串?我对s3一无所知,但我认为这可能有所帮助。 - Vercas
我不想先将图像保存到文件中,因为这样会增加额外的负担。我相信在图像仍在内存中时就可以完成操作。 - Abs
然后将其保存到内存流中。 - Vercas
2个回答

15
您可以使用 WithInputStream 或者 WithFilePath。例如,在将新图片保存到 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);
    }
}

好的,这很有道理。我该如何将Bitmap对象转换为内存流?如果这是一个简单的问题,那么请原谅,因为我在C#方面还是个新手。 - Abs
1
@Abs:我更新了代码示例,包括将位图保存到内存流的示例。 - vcsjones
@vcsjones - 它在 using 块内。完整函数请参见此处:http://pastebin.com/5dTiZ8Di - 非常感谢您一直以来的帮助!第 20 行是罪魁祸首。 - Abs
1
@Abs:你的 client.PutObject(titledRequest); 调用应该在 using 语句内部(在第16行和第17行之间)。 - vcsjones
@vcsjones - 太棒了!感谢您的帮助。对于像我这样的C#新手来说,非常感激。 - Abs
显示剩余3条评论

2

将请求对象的InputStream属性设置为:

titledRequest.InputStream = image;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接