1

这是我的 aspx 代码:

<asp:FileUpload ID="FileUpload2" runat="server" Width="500px" />
            <asp:Button ID="btnUploadImg" runat="server" onclick="btnNahrajObrazek_Click" Text="Nahrát obrázek" Height="35px" Width="150px" />

这是我背后的代码:

protected void btnUploadImg_Click(object sender, EventArgs e)
    {
        string input = Request.Url.AbsoluteUri;
        string output = input.Substring(input.IndexOf('=') + 1);
        string fileName = Path.GetFileName(FileUpload2.PostedFile.FileName);

        int width = 800;
        int height = 600;
        Stream stream = FileUpload2.PostedFile.InputStream;

        Bitmap image = new Bitmap(stream);

        Bitmap target = new Bitmap(width, height);
        Graphics graphic = Graphics.FromImage(target);
        graphic.DrawImage(image, 0, 0, width, height);
        target.Save(Server.MapPath("~/Uploads/" + output + "/") + fileName);
    }

我想保持正在上传的图像的纵横比,所以我只需要设置宽度或设置宽度,如 100% 和高度 400 或类似的东西?但是不知道怎么做。

如果这是不可能的,图像裁剪就足够了,但我想先更好。

提前致谢!

4

1 回答 1

2

所以这是我根据我在这里找到的解决方案:http: //www.nerdymusings.com/LPMArticle.asp?ID=32

string input = Request.Url.AbsoluteUri;
        string output = input.Substring(input.IndexOf('=') + 1);
        string fileName = Path.GetFileName(FileUpload2.PostedFile.FileName);

        Stream stream = FileUpload2.PostedFile.InputStream;

        Bitmap sourceImage = new Bitmap(stream);

        int maxImageWidth = 800;

        if (sourceImage.Width > maxImageWidth)
        {
            int newImageHeight = (int)(sourceImage.Height * ((float)maxImageWidth / (float)sourceImage.Width));
            Bitmap resizedImage = new Bitmap(maxImageWidth, newImageHeight);
            Graphics gr = Graphics.FromImage(resizedImage);
            gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
            gr.DrawImage(sourceImage, 0, 0, maxImageWidth, newImageHeight);
            // Save the resized image:
            resizedImage.Save(Server.MapPath("~/Uploads/" + output + "/") + fileName);
        }
        else
        {
            sourceImage.Save(Server.MapPath("~/Uploads/" + output + "/") + fileName);
        }

我认为这很简单,也很有效。

于 2013-04-08T12:00:43.493 回答