1

I have a large number of images on a Web server that need to be cropped. I would like to automate this process.

So my thought is to create a routine that, given the URL of the image, downloads the image, crops it, then uploads it back to the server (as a different file). I don't want to save the image locally, and I don't want to display the image to the screen.

I already have a project in C#.Net that I'd like to do this in, but I could do .Net Core if I have to.

I have looked around, but all the information I could find for downloading an image involves saving the file locally, and all the information I could find about cropping involves displaying the image to the screen.

Is there a way to do what I need?

ScottM
  • 121
  • 1
  • 4

1 Answers1

0

It's perfectly possible to issue a GET request to a URL and have the response returned to you as a byte[] using HttpClient.GetByteArrayAsync. With that binary content, you can read it into an Image using Image.FromStream.

Once you have that Image object, you can use the answer from here to do your cropping.

//Note: You only want a single HttpClient in your application 
//and re-use it where possible to avoid socket exhaustion issues
using (var httpClient = new HttpClient())
{
    //Issue the GET request to a URL and read the response into a 
    //stream that can be used to load the image
    var imageContent = await httpClient.GetByteArrayAsync("<your image url>");
    
    using (var imageBuffer = new MemoryStream(imageContent))
    {
        var image = Image.FromStream(imageBuffer);

        //Do something with image
    }
}
lee-m
  • 2,269
  • 17
  • 29