Reputation: 3640
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
Upvotes: 4
Views: 3054
Reputation: 5665
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);
}
Upvotes: 9
Reputation: 11514
Here is an example uploading a blob that you have as a Stream
. It uses the Azure client SDK:
private async Task WriteBlob(Stream blob, string containerName, string blobPath)
{
// 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);
// Create the container if it doesn't already exist.
await container.CreateIfNotExistsAsync();
// create a blob in the path of the <container>/email/guid
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobPath);
await blockBlob.UploadFromStreamAsync(blob);
}
Upvotes: 0