On Media Library Upload

ravi bhadri asked on August 22, 2016 12:15

Hello All,

I have a requirement like on upload of an image into media library, I should get 3 images in different sizes. Is this possible through kentico API(Kentico 8.2 API)?

Please help me with this.

Thanks in advance.

Recent Answers


Richard Sustek answered on August 22, 2016 13:48 (last edited on August 24, 2016 10:13)

You can use Global events for MediaFileInfo object. If you bind it to Insert action that your method will be executed whenever a new media file is created (uploaded) in Kentico.

This global event may look like:

MediaFileInfo.TYPEINFO.Events.Insert.After += Insert_After;

and:

private void Insert_After1(object sender, ObjectEventArgs e)
{
    var mediaFile = e.Object as MediaFileInfo;

    if (mediaFile != null)
    {
        // get path to media file
        var filePath = mediaFile.FilePath;

        // check if it is jpg or one of your supported file types...
        if (mediaFile.FileExtension.Equals("jpg", StringComparison.OrdinalIgnoreCase))
        {
            // Resize and save image here
        }
    }
}

In the past I've used following code to resize an image:

int height = 50;
int width = 50;

string filePath = Server.MapPath("~") + "\\SomeFolder\\OriginalPicture.png";
string newfilePath = Server.MapPath("~") + "\\SomeFolder\\ResizedPicture.png";

// load image
var imageHelper = new ImageHelper(CMS.IO.File.ReadAllBytes(filePath));

// resize image
var resizedImage = imageHelper.GetResizedImage(width, height);

// save image
resizedImage.Save(newfilePath);    
1 votesVote for this answer Mark as a Correct answer

ravi bhadri answered on August 24, 2016 09:35

Hi Rechard,

Thanks for the response. But in insertAfter event also image is not getting uploaded into media library/database, so I am unable to create ImageHelper class object.

0 votesVote for this answer Mark as a Correct answer

Jono Rickard answered on November 15, 2017 17:39

Hey Ravi,

I know this is a year later, but you can access the mediaFile.FileBinary or mediaFile.FileBinaryStream from the Insert_After event, even though it may not be finished uploading itself.

Cheers Jono

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.