Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading a Bitmap object to Azure blob storage

I'm trying to download, resize and then upload an image to Azure blob storage.

I can download the original image and resize it like so:

private bool DownloadandResizeImage(string originalLocation, string filename)
    {
        try
        {
            byte[] img;
            var request = (HttpWebRequest)WebRequest.Create(originalLocation);

            using (var response = request.GetResponse())
            using (var reader = new BinaryReader(response.GetResponseStream()))
            {
                img = reader.ReadBytes(200000);
            }

            Image original;

            using (var ms = new MemoryStream(img))
            {
                original = Image.FromStream(ms);
            }

            const int newHeight = 84;
            var newWidth = ScaleWidth(original.Height, 84, original.Width);

            using (var newPic = new Bitmap(newWidth, newHeight))
            using (var gr = Graphics.FromImage(newPic))
            {
                gr.DrawImage(original, 0, 0, newWidth, newHeight);
                // This is where I save the file, I would like to instead
                // upload it to Azure
                newPic.Save(filename, ImageFormat.Jpeg);


            }

            return true;
        }
        catch (Exception e)
        {
            return false;
        }

    }

I know I can use UploadFromFile to upload the saved file, but wondering if there is a way to do it directly from my object so I don't have to save it first? I've tried upload from stream, and can do that after the using ms function, but then I resize the file

like image 697
Evonet Avatar asked Feb 07 '23 22:02

Evonet


1 Answers

Just to complete Crowcoder's answer a bit in the context of the whole question, I think what you need is:

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_blobcnxn);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve a reference to a container.
CloudBlobContainer container = blobClient.GetContainerReference(containerName);

using (MemoryStream memoryStream = new MemoryStream())
{
    newPic.Save(memoryStream, ImageFormat.Jpeg);
    memoryStream.Seek(0, SeekOrigin.Begin); // otherwise you'll get zero byte files
    CloudBlockBlob blockBlob = jpegContainer.GetBlockBlobReference(filename);
    blockBlob.UploadFromStream(memoryStream);
}
like image 90
Chris Rae Avatar answered Feb 16 '23 02:02

Chris Rae