SupposedlySam
SupposedlySam

Reputation: 685

Azure Blob TIFF to PNG Conversion Without Download

I'm trying to figure out a way to show a tiff image (pulled from Azure blob storage) in an img tag without using a tiff viewer. My first thought is to convert the image from a tiff to a png then show it in the browser as a base64 encoded image.

I've seen the Image.Save method being used a lot but I can't seem to figure out how to use it without saving the image to disk.

Is there a way I can convert the tiff to a png on the fly so it will render in browsers?

Code to work from

public ActionResult Index()

{
    CloudBlobContainer blobContainer = GetContainer(documentsContainerName);
    IEnumerable<string> blobs = blobContainer.ListBlobs().Select(blob =>
    {
        CloudBlockBlob blockBlob = (CloudBlockBlob)blob;

        using (MemoryStream blockBlobStream = new MemoryStream())
        {
            blockBlob.DownloadToStream(blockBlobStream);

            using (MemoryStream ms = new MemoryStream())
            {
                using (Image img = Image.FromStream(blockBlobStream))
                {
                    img.Save(ms, ImageFormat.Png);
                }

                StreamReader reader = new StreamReader(ms);

                byte[] bytedata = System.Text.Encoding.Default.GetBytes(reader.ReadToEnd());

                string strBase64 = System.Convert.ToBase64String(bytedata);

                return strBase64;
            }
        }
    });

    return View("Index", "", blobs);
}

Upvotes: 0

Views: 1466

Answers (2)

SupposedlySam
SupposedlySam

Reputation: 685

Per @Dai's suggestion I was able to convert my blob to a png using Magick.Net nuget package.

using (MemoryStream memStream = new MemoryStream())
{
    using (MagickImage image = new MagickImage(byteArray))
    {
        image.Format = MagickFormat.Png;
        image.Write(memStream);
    }
    return System.Convert.ToBase64String(memStream.ToArray());
}

Upvotes: 3

Leonardo
Leonardo

Reputation: 11401

as per documentation (https://msdn.microsoft.com/en-us/library/ms142147(v=vs.110).aspx) you can create a memory stream and save the image directly to it, instead of the disk.

Edit 1:
Guessing that you're using some sort of API, you can return the string representation of that img, have your client side JS save it on the client machine cache and alter your <img src=""/> to the proper location...

Edit 2:
A better way would be, upon upload, convert the tiff to png and store it along and then only reference it as a regular blob on your page... this way you save a lot of CPU power cause you won't be converting tiff as needed, but only once.

Upvotes: 1

Related Questions