Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a file to a bucket on Amazon S3 using C#

Tags:

c#

.net

amazon-s3

How can I save a bitmap object as an image to Amazon S3?

I've got everything setup but my limited C sharp is stopping me from getting this done.

// 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);

As you can see the S3 function can only take in a string and save it as the body of the file.

How can I write this in such a way that it will allow me pass in a bitmap object and save it as an image? Maybe as a stream? Or as a byte array?

I appreciate any help.

like image 533
Abs Avatar asked Jun 25 '11 13:06

Abs


People also ask

How do I import a CSV file into an S3 bucket?

Navigate to All Settings > Raw Data Export > CSV Upload. Toggle the switch to ON. Select Amazon S3 Bucket from the dropdown menu. Enter your Access Key ID, Secret Access Key, and bucket name.


1 Answers

You would use WithInputStream or WithFilePath. For example on saving a new image to 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);
    }
}
like image 125
vcsjones Avatar answered Oct 20 '22 07:10

vcsjones