我怎样才能下载时调整图像大小? [英] How can I resize an image when downloading?

查看:161
本文介绍了我怎样才能下载时调整图像大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要调整图片的大小,当我下载它,或者下载后。这是我的code。质量并不重要。

I want to resize my image when I am downloading it, or after download. This is my code. Quality is not important.

public void downloadPicture(string fileName, string url,string path) {
        string fullPath = string.Empty;
        fullPath = path + @"\" + fileName + ".jpg"; //imagePath
        byte[] content;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        WebResponse response = request.GetResponse();

        Stream stream = response.GetResponseStream();

        using (BinaryReader br = new BinaryReader(stream)) {
            content = br.ReadBytes(500000);
            br.Close();
        }
        response.Close();

        FileStream fs = new FileStream(fullPath, FileMode.Create); // Starting create
        BinaryWriter bw = new BinaryWriter(fs);
        try {
            bw.Write(content); // Created
        }
        finally {
            fs.Close();
            bw.Close();
        }
    }

所以,我该怎么办呢?

So how can I do it?

推荐答案

将这个code在try / finally块后 -

Put this code after the try / finally block -

这将调整图像到1/4原来的大小。

This will resize the image to 1/4 its original size.

        using (System.Drawing.Image original = System.Drawing.Image.FromFile(fullPath))
        {
            int newHeight = original.Height / 4;
            int newWidth = original.Width / 4;

            using (System.Drawing.Bitmap newPic = new System.Drawing.Bitmap(newWidth, newHeight))
            {
                using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(newPic))
                {
                    gr.DrawImage(original, 0, 0, (newWidth), (newHeight));
                    string newFilename = ""; /* Put new file path here */
                    newPic.Save(newFilename, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
        }

当然,你可以把它改成任何你想要的大小,通过改变newHeight和newWidth变量

You can of course change it to any size you want, by changing the newHeight and newWidth variables

更新:修改code使用使用(){},而不是部署,按照下面的评论

UPDATE: modified code to use using() {} instead of dispose, as per comment below.

这篇关于我怎样才能下载时调整图像大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆