2015-09-10 140 views
0

Iam将图像绘制到图片框。我根据宽度和高度调整图片框中的图片大小,以便正确放入picutrebox中。之后,我想保存它,同时保存它,我也想保存非保存文件中的非图像绘制部分。请看截图,截图中我有2个白色部分标记为'X'。当我将图像保存在picturebox中时,我也想将空白部分保存为红色(作为透明.png)或纯白色.jpg。从Picturebox保存图像

其实我从谷歌复制的代码的一些部分和修改。如果有人请逐行解释,这将会非常有用。

enter image description here


这是我有donw到目前为止,

private void button1_Click(object sender, EventArgs e) 
    { 
     OpenFileDialog open = new OpenFileDialog(); 
     open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp; *.png)|*.jpg; *.jpeg; *.gif; *.bmp; *.png"; 
     if (open.ShowDialog() == DialogResult.OK) 
     {    
      Image original = Bitmap.FromFile(open.FileName); 
      pictureBox1.Image = new Bitmap(ScaleImage(original)); 

      pictureBox1.Padding = new Padding((pictureBox1.Width - ScaleImage(original).Width)/2, (pictureBox1.Height - ScaleImage(original).Height)/2, 0, 0); 
     } 
    } 

    private Bitmap ScaleImage(Image oldImage) 
    { 
     double resizeFactor = 1; 

     if (oldImage.Width > 300 || oldImage.Height > 300) 
     { 
      double widthFactor = Convert.ToDouble(oldImage.Width)/300; 
      double heightFactor = Convert.ToDouble(oldImage.Height)/125; 
      resizeFactor = Math.Max(widthFactor, heightFactor); 
     } 

     int width = Convert.ToInt32(oldImage.Width/resizeFactor); 
     int height = Convert.ToInt32(oldImage.Height/resizeFactor); 
     Bitmap newImage = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 

     newImage.MakeTransparent(Color.White); 

     Graphics g = Graphics.FromImage(newImage); 

     g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
     g.DrawImage(oldImage, 0, 0, newImage.Width, newImage.Height); 
     return newImage; 
    } 
    private void button2_Click(object sender, EventArgs e) 
    { 
     pictureBox1.BackColor = Color.White; 
     pictureBox1.Image.Save("D:\\temp.png", ImageFormat.Png); 
    } 
+0

当前iam将图像保存在图片框中。我想我必须保存整个图画盒或类似的东西。当我救我也想保持我的形象不变。在交叉的地方添加透明度或纯色。 – locknies

+0

如果其他人建议添加图像的其他选项,调整大小并保存它没有picturebox也欢迎! – locknies

+0

我真的不明白这里的目标是什么。它是保存调整大小的图片,还是将图片显示在图片框中? 那么你基本上想要的是调整图片的大小以适应堆积比例的白色或透明的空白部分? – Matyas

回答

3

我希望这可以帮助。尝试使用它来保存调整大小的图像(我猜想在button2_Click)。

using (Bitmap bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height)) 
{ 
    using (Graphics graphics = Graphics.FromImage(bitmap)) 
    { 
     graphics.Clear(Color.Transparent); 
     graphics.DrawImage(pictureBox1.Image, (bitmap.Width - pictureBox1.Image.Width)/2, (bitmap.Height - pictureBox1.Image.Height)/2); 
    } 

    bitmap.Save(@"D:\tmpMod.png", ImageFormat.Png); 
}