将图像保存为矩形

时间:2015-09-17 06:44:02

标签: c# asp.net

我正在尝试将图像保存在一个填充红色的矩形中,但我得到的文件不是图像,这是我的代码:

protected void btnDrowRect_Click(object sender, EventArgs e)
    {

    string fn1 = Session["WorkingImage"].ToString();

    string imagePath = Server.MapPath("~/Images/rec" + fn1);
    string savetoo = Server.MapPath("~/Images/rect/rec" + DateTime.Now.ToString("hhmmss"));
   string imageNewPath = savetoo; ;

    Image image = Image.FromFile(imagePath);

    int a = Int32.Parse(imgw.Value) / 2 - img3.Width / 2;
    int b = Int32.Parse(imgh.Value) / 2 - img3.Height / 2;

    Rectangle srcRect = new Rectangle(-a, -b, Int32.Parse(imgw.Value),Int32.Parse(imgh.Value));
    Bitmap bmp = new Bitmap(Int32.Parse(imgw.Value), Int32.Parse(imgh.Value));
    using (Graphics g = Graphics.FromImage(bmp))
    {
        // Create image.
        Image newImage = Image.FromFile(imagePath);

        // Create rectangle for displaying image.
        Rectangle destRect = new Rectangle(0, 0, Int32.Parse(imgw.Value), Int32.Parse(imgh.Value));

        // Create rectangle for source image.

        GraphicsUnit units = GraphicsUnit.Pixel;

        Color customColor = Color.FromArgb(100, Color.Red);
        SolidBrush shadowBrush = new SolidBrush(customColor);
        g.FillRectangles(shadowBrush, new RectangleF[] { destRect });

        // Draw image to screen.
        g.DrawImage(newImage, destRect, srcRect, units);
        // g.Save();

    }

    bmp.Save(imageNewPath);

}

单击此处查看已保存的文件:

  

http://i.stack.imgur.com/Nso3c.png

但我希望像这样得救:

  

http://i.stack.imgur.com/B7CUl.png

1 个答案:

答案 0 :(得分:0)

你可以尝试

string savetoo = Server.MapPath("~/Images/rect/rec" + DateTime.Now.ToString("hhmmss") + ".jpg");

bmp.Save(imageNewPath, ImageFormat.Jpeg); 

它会起作用