Resize the image on the server and then upload to azure

I have the following function which I am using to upload files to azure account.

As you will see, it does not resize, etc .:

public string UploadToCloud (FileUpload fup, string containerName) {// Retrieve the storage account from the connection string. CloudStorageAccount storageAccount = CloudStorageAccount.Parse (ConfigurationManager.AppSettings ["StorageConnectionString"]);

    // Create the blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve a reference to a container. 
    CloudBlobContainer container = blobClient.GetContainerReference(containerName);

    string newName = "";
    string ext = "";
    CloudBlockBlob blob = null;


    // Create the container if it doesn't already exist.
    container.CreateIfNotExists();

    newName = "";
    ext = Path.GetExtension(fup.FileName);

    newName = string.Concat(Guid.NewGuid(), ext);

    blob = container.GetBlockBlobReference(newName);

    blob.Properties.ContentType = fup.PostedFile.ContentType;

    //S5: Upload the File as ByteArray            
    blob.UploadFromStream(fup.FileContent);

    return newName;


}

      

Then I have this function that I have used on non-azure sites:

public string ResizeandSave(FileUpload fileUpload, int width, int height, bool deleteOriginal, string tempPath = @"~\tempimages\", string destPath = @"~\cmsgraphics\")
        {
            fileUpload.SaveAs(Server.MapPath(tempPath) + fileUpload.FileName);

            var fileExt = Path.GetExtension(fileUpload.FileName);
            var newFileName = Guid.NewGuid().ToString() + fileExt;

            var imageUrlRS = Server.MapPath(destPath) + newFileName;

            var i = new ImageResizer.ImageJob(Server.MapPath(tempPath) + fileUpload.FileName, imageUrlRS, new ImageResizer.ResizeSettings(
                            "width=" + width + ";height=" + height + ";format=jpg;quality=80;mode=max"));

            i.CreateParentDirectory = true; //Auto-create the uploads directory.
            i.Build();

            if (deleteOriginal)
            {
                var theFile = new FileInfo(Server.MapPath(tempPath) + fileUpload.FileName);

                if (theFile.Exists)
                {
                    File.Delete(Server.MapPath(tempPath) + fileUpload.FileName);
                }
            }

            return newFileName;
        }

      

Now what I'm trying to do is try to combine the two ... or at least work out a way to resize the image before saving it to the azure image.

Does anyone have any idea?

+3


source to share


2 answers


I hope you got it working already, but I was looking for some working solution today, I can't find it. But finally I did it.

Here is my code, hope it helps someone:



    /// <summary>
    /// Saving file to AzureStorage
    /// </summary>
    /// <param name="containerName">BLOB container name</param>
    /// <param name="MyFile">HttpPostedFile</param>
    public static string SaveFile(string containerName, HttpPostedFile MyFile, bool resize, int newWidth, int newHeight)
    {
        string fileName = string.Empty;

        try
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);
            container.CreateIfNotExists(BlobContainerPublicAccessType.Container);

            string timestamp = Helper.GetTimestamp() + "_";
            string fileExtension = System.IO.Path.GetExtension(MyFile.FileName).ToLower();
            fileName = timestamp + MyFile.FileName;

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
            blockBlob.Properties.ContentType = MimeTypeMap.GetMimeType(fileExtension);

            if (resize)
            {
                Bitmap bitmap = new Bitmap(MyFile.InputStream);

                int oldWidth = bitmap.Width;
                int oldHeight = bitmap.Height;

                GraphicsUnit units = System.Drawing.GraphicsUnit.Pixel;
                RectangleF r = bitmap.GetBounds(ref units);
                Size newSize = new Size();

                float expectedWidth = r.Width;
                float expectedHeight = r.Height;
                float dimesion = r.Width / r.Height;

                if (newWidth < r.Width)
                {
                    expectedWidth= newWidth;
                    expectedHeight = expectedWidth/ dimesion;
                }
                else if (newHeight < r.Height)
                {
                    expectedHeight = newHeight;
                    expectedWidth= dimesion * expectedHeight;
                }
                if (expectedWidth> newWidth)
                {
                    expectedWidth= newWidth;
                    expectedHeight = expectedHeight / expectedWidth;
                }
                else if (nPozadovanaVyska > newHeight)
                {
                    expectedHeight = newHeight;
                    expectedWidth= dimesion* expectedHeight;
                }
                newSize.Width = (int)Math.Round(expectedWidth);
                newSize.Height = (int)Math.Round(expectedHeight);

                Bitmap b = new Bitmap(bitmap, newSize);

                Image img = (Image)b;
                byte[] data = ImageToByte(img);

                blockBlob.UploadFromByteArray(data, 0, data.Length);
            }
            else
            {
                blockBlob.UploadFromStream(MyFile.InputStream);
            }                
        }
        catch
        {
            fileName = string.Empty;
        }

        return fileName;
    }

    /// <summary>
    /// Image to byte
    /// </summary>
    /// <param name="img">Image</param>
    /// <returns>byte array</returns>
    public static byte[] ImageToByte(Image img)
    {
        byte[] byteArray = new byte[0];
        using (MemoryStream stream = new MemoryStream())
        {
            img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            stream.Close();

            byteArray = stream.ToArray();
        }
        return byteArray;
    }

      

+1


source


I am doing a resize operation in a Windows Phone 8 app. As you can imagine that the runtime for WP8 is much limited compared to the entire .NET runtime, so there might be other options to do it more efficiently if you don't have those the same restrictions as me.

public static void ResizeImageToUpload(Stream imageStream, PhotoResult e)
    {            
        int fixedImageWidthInPixels = 1024;
        int verticalRatio = 1;

        BitmapImage bitmap = new BitmapImage();
        bitmap.SetSource(e.ChosenPhoto);
        WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap);
        if (bitmap.PixelWidth > fixedImageWidthInPixels)
            verticalRatio = bitmap.PixelWidth / fixedImageWidthInPixels;
        writeableBitmap.SaveJpeg(imageStream, fixedImageWidthInPixels,
            bitmap.PixelHeight / verticalRatio, 0, 80);                                       
    }

      



The code will resize the image if its width is greater than 1024 pixels. The variable is verticalRatio

used to compute the aspect ratio of the image so that it does not lose its aspect ratio during resizing. The code then encodes the new jpeg using 80% of the original image quality.

Hope it helps

0


source







All Articles