Resize image BEFORE uploading to Azure blob storage

1.7k Views Asked by At

i am trying to resize an image using the WebImage helper BEFORE uploading to Azure blob, using the following code, but getting this error:

cannot convert from 'system.web.helpers.webimage' to 'system.io.stream'

The code is as follows:

    public async Task<string> UploadPropertyImageAsync(HttpPostedFileBase imageToUpload)
    {
        string imageFullPath = null;
        if (imageToUpload == null || imageToUpload.ContentLength == 0 || imageToUpload.ContentLength >= 8388608)
        {
            return null;
        }
        //Image img = System.Drawing.Image.FromStream(imageToUpload);
        WebImage img = new WebImage(imageToUpload.InputStream);
        if (img.Width > 1000)
            img.Resize(1000, 1000); 
        try
        {
            CloudStorageAccount cloudStorageAccount = ConnectionString.GetConnectionString();
            CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("property");

            if (await cloudBlobContainer.CreateIfNotExistsAsync())
            {
                await cloudBlobContainer.SetPermissionsAsync(
                    new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    }
                    );
            }
            string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(img.FileName);

            CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);
            cloudBlockBlob.Properties.ContentType = img.ContentType;
            await cloudBlockBlob.UploadFromStreamAsync(img);

Any idea where i'm going wrong?

2

There are 2 best solutions below

0
Gaurav Mantri On BEST ANSWER

CloudBlockBlob.UploadFromStreamAsync expects a stream which your WebImage object is not and hence you're getting this error.

What you would need to do is convert the image into a stream. I looked up the documentation and there's no direct method to do so.

However you can get the bytes from the WebImage using WebImage.GetBytes and then use CloudBlockBlob.UploadFromByeArrayAsync method to upload that byte array as blob in Azure Storage.

1
Mike Gledhill On

The exception is pretty self explanatory.

This line is expecting a Stream, not a WebImage variable.

await cloudBlockBlob.UploadFromStreamAsync(img);

There are plenty of examples showing how to upload files to Azure, for example:

Uploading to Azure

... and here...

An Introduction to Windows Azure BLOB Storage