简体   繁体   English

C#.Net 从 URL 下载图像,裁剪和上传,无需保存或显示

[英]C#.Net Download Image from URL, Crop, and Upload without Saving or Displaying

I have a large number of images on a Web server that need to be cropped.我在 Web 服务器上有大量需要裁剪的图像。 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).所以我的想法是创建一个例程,给定图像的 URL,下载图像,裁剪它,然后将其上传回服务器(作为不同的文件)。 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.我已经在 C#.Net 中有一个项目,我想在其中执行此操作,但如果必须,我可以执行.Net Core。

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?有没有办法做我需要的?

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 .完全可以向 URL 发出 GET 请求,并使用HttpClient.GetByteArrayAsync将响应作为byte[]返回给您。 With that binary content, you can read it into an Image using Image.FromStream .使用该二进制内容,您可以使用Image.FromStream将其读入Image

Once you have that Image object, you can use the answer from here to do your cropping.一旦您拥有该Image object,您就可以使用此处的答案进行裁剪。

//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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM