Friday 20 June 2014

MVC, ImageResizer, Windows Azure and Creating a Thumbnail Image

Ok you will need the nuget package for ImageResizer, you will not need any of the plugins for this to work, just so you are aware. Use: Package Manager, make sure you have the right project in the dropdown and type: Install-Package ImageResizer [enter]

This example below will take your file, created it in azure and also create thumbnail, it needs to create 2 seperate streams for this.  Before the the StreamUploadFile is called we do a check for any image types we want as thumnbnails, there is a probably a better way to this, but I had to get it done quick(quick isn't always slick :).  On the GetThumbnail Method on the controller is where it will return the image stream, we also have a fallback in case there is no image to display.

Azure Document Manager Class:

        public void StreamUploadFile(string myContainer, string fileName, HttpPostedFileBase file, bool isImage)
        {
            try
            {
                // Retrieve reference to a previously created container.
                var container = _blobClient.GetContainerReference(myContainer);
               
                // Create the container if it doesn't already exist.
                container.CreateIfNotExists();

                // Retrieve reference to a blob named "myblob".
                var blockBlob = container.GetBlockBlobReference(fileName);

                // Create Thumbnail If it is an image
                if (isImage)
                {
                    //Stream fileStreamThumb;
                 

                    // Copy File Stream
                    MemoryStream fileStreamThumb = new MemoryStream();
                    file.InputStream.CopyTo(fileStreamThumb);

                    fileStreamThumb.Seek(0, SeekOrigin.Begin);
                    string thumbnailUri = String.Concat(Path.GetFileNameWithoutExtension(fileName),
                        "_thumb" + Path.GetExtension(fileName));

                    CloudBlockBlob thumbnailBlob = container.GetBlockBlobReference(thumbnailUri);
                    thumbnailBlob.UploadFromStream(CreateThumbnail(fileStreamThumb));
                }

                // Create or overwrite the "myblob" blob with contents from a local file.
                using (var fileStream = file.InputStream)
                {
                    fileStream.Seek(0, SeekOrigin.Begin);
                    blockBlob.UploadFromStream(fileStream);
                }
            }
           
            catch (Exception ex)
            {
                _exceptionHandler.Invoke(ex);
            }
        }

// For Image Resizing
        public Stream CreateThumbnail(Stream input)
        {
            var output = new MemoryStream();
           
            ImageResizer.ImageJob i = new ImageResizer.ImageJob(input, output, new ImageResizer.ResizeSettings("width=100;height=100;mode=max"));
            i.Build();

             
            output.Seek(0, SeekOrigin.Begin);
            return output;
         }

  public byte[] ReturnFileStream(string filePath, string myContainer, string myFile)
        {
            try
            {
                // Retrieve reference to a previously created container.
                var container = _blobClient.GetContainerReference(myContainer);

                // Retrieve reference to a blob named "photo1.jpg".
                var blockBlob = container.GetBlockBlobReference(@myFile);

                // Save blob contents to a file.
                var sStream = new MemoryStream();
                using (var fileStream = File.OpenWrite(filePath))
                {
                    blockBlob.DownloadToStream(sStream);
                }
                return sStream.ToArray();
            }
            catch (Exception ex)
            {
                _exceptionHandler.Invoke(ex);
                return null;
            }
        }


MVC Controler Method:

 public FileContentResult GetThumbnail(int id = 0)
        {
            try
            {
                // Needs a bit of tidying up
                var document = db.Documents.Find(id);
                if (document == null) return null;
                var container = ((int) document.SurveyID).ToString("D8");
                var azureDocument =
                    new DocumentManager.AzureDocumentManager(
                        Encryption.DecryptStorageConnectionString(_storageConnection), null);
                var temp =
                    azureDocument.ReturnFileStream(
                        Path.GetTempPath() + Path.GetFileNameWithoutExtension(document.Name) + "_thumb" +
                        Path.GetExtension(document.Name), container,
                        Path.GetFileNameWithoutExtension(document.Name) + "_thumb" + Path.GetExtension(document.Name));
                var temp2 = new FileContentResult(temp, "application/text") {FileDownloadName = document.Name};
                return temp2;
            }
            catch (Exception ex)
            {
                var fileName =   Server.MapPath("..\\..\\images") + "\\missing.png";

                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    // Get Error Image
                    MemoryStream input = new MemoryStream();
                    fs.CopyTo(input);
                    input.Seek(0, System.IO.SeekOrigin.Begin);

                    // Resize
                    var output = new MemoryStream();
                    ImageResizer.ImageJob i = new ImageResizer.ImageJob(input, output, new ImageResizer.ResizeSettings("width=64;height=64;mode=pad"));
                    i.Build();
                    output.Seek(0, SeekOrigin.Begin);

                    // Ouput Image
                    var temp2 = new FileContentResult(output.ToArray(), "application/text") { FileDownloadName = "error.jpg" };
                    return temp2;
                }
            }
            finally
            {
            }
           }

Hoepfully that should solve a few headaches or create more in some cases, let me know if there is nothing clear on here :D

No comments: