调整和保存从远程URL下载的c#中的图像

时间:2015-03-19 22:28:00

标签: c#

我有一些代码可以从远程URL下载文件并非常有效地保存它。

当我保存它时,如何修改此高度以将高度设置为120px(以及相应的宽度比例)?

    private static bool DownloadRemoteImageFile(string uri, string fileName)
    {


        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        HttpWebResponse response;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
        }
        catch (Exception)
        {
            return false;
        }

        if ((response.StatusCode == HttpStatusCode.OK ||
            response.StatusCode == HttpStatusCode.Moved ||
            response.StatusCode == HttpStatusCode.Redirect) &&
            response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
        {

            using (Stream inputStream = response.GetResponseStream())
            using (Stream outputStream = System.IO.File.OpenWrite(fileName))
            {
                var buffer = new byte[4096];
                int bytesRead;
                do
                {
                    bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                    outputStream.Write(buffer, 0, bytesRead);
                } while (bytesRead != 0);
            }
            return true;
        }

        return false;
    }

我见过的示例使用的是我没有使用的Bitmap类,我是否需要更改下载文件的方式?

1 个答案:

答案 0 :(得分:3)

更新您的DownloadRemoteImageFile方法以返回byte[]

private static byte[] DownloadRemoteImageFile(string uri)
{
    byte[] content;
    var request = (HttpWebRequest)WebRequest.Create(uri);

    using (var response = request.GetResponse())
    using (var reader = new BinaryReader(response.GetResponseStream()))
    {
        content = reader.ReadBytes(100000);
    }

    return content;
}

然后使用System.Drawing类重新调整大小并保存图像:

static void Main(string[] args)
{
    var img = DownloadRemoteImageFile( // Put your url here );

    Image original;

    using (var ms = new MemoryStream(img))
    {
        original = Image.FromStream(ms);
    }

    var newHeight = 120;
    var newWidth = ScaleWidth(original.Height, 120, original.Width);

    using (var newPic = new Bitmap(newWidth, newHeight))
    using (var gr = Graphics.FromImage(newPic))
    {
        gr.DrawImage(original, 0, 0, newWidth, newHeight);
        newPic.Save(@"C:\newImage1.jpg", ImageFormat.Jpeg);
    }
}

缩放宽度:

private static int ScaleWidth(int originalHeight, int newHeight, int originalWidth)
{
    var scale = Convert.ToDouble(newHeight) / Convert.ToDouble(originalHeight);

    return Convert.ToInt32(originalWidth * scale);
}