2012-01-24 28 views
0

我有一个函数:到边框飞度形象,用黑色填充,其余在C#

private static Image ScaleAndPadBlack(Image original_img, Thumbnail thumb) 
    { 
     if (thumb.OptimalSizeHeight <= 0) 
     { 
      throw new ArgumentOutOfRangeException("OptimalSizeHeight", "OptimalSizeHeight must be declared and positive when using the ScaleAndCrop method."); 
     } 
     if (thumb.OptimalSizeWidth <= 0) 
     { 
      throw new ArgumentOutOfRangeException("OptimalSizeWidth", "OptimalSizeWidth must be declared and positive when using the ScaleAndCrop method."); 
     } 

     Size dest_size = new Size(thumb.OptimalSizeWidth, thumb.OptimalSizeHeight); 

     decimal act_width_rate = (decimal)dest_size.Width/(decimal)original_img.Width; 
     decimal act_height_rate = (decimal)dest_size.Height/(decimal)original_img.Height; 

     decimal scale_rate; 
     if (act_width_rate <= act_height_rate) 
      scale_rate = act_width_rate; 
     else 
      scale_rate = act_height_rate; 

     Size act_size = new Size(Convert.ToInt32(original_img.Width * scale_rate), Convert.ToInt32(original_img.Height * scale_rate)); 

     var res = resizeImage(original_img, act_size); 

     var b = new Bitmap(thumb.OptimalSizeWidth, thumb.OptimalSizeHeight); 
     var g = Graphics.FromImage(b); 

     Point p = new Point(((dest_size.Width - act_size.Width)/2), ((dest_size.Height - act_size.Height)/2)); 
     g.FillRectangle(Brushes.Black, new Rectangle(new Point(0, 0), dest_size)); 
     g.SmoothingMode = SmoothingMode.None; 
     g.InterpolationMode = InterpolationMode.NearestNeighbor; 
     g.DrawImage(res, p); 
     res.Dispose(); 
     res = null; 
     return b; 
    } 

这样做是它调整图像大小以适应边框内,创建一个新的形象,填补它带有黑色,并将调整后的图像放在黑色图像上。

的问题是,调整全白JPG(761x896)图像为270x180边框的结果是:

Greyish bar on top

你可以看到,有在图像的顶部的灰色条这是因为调整大小的图像以某种方式具有透明边缘。

这是怎么发生的?调整图像大小可能导致透明边缘?在这种情况下,这绝对不是理想的。

或者是因为某些其他原因而出现顶部边缘?

我应该如何编写这样的函数,在这种情况下没有黑灰色边缘?我只想填充没有图像的部分,我应该做一些完全不同的事情吗?

编辑:

的g.SmoothingMode = SmoothingMode.None; g.InterpolationMode = InterpolationMode.NearestNeighbor;在那里,因为我正在测试这个问题。他们似乎并不重要。

+0

你确定这是一个透明的边缘吗? – annonymously

+0

您可以看到生成的图片。我不确定。我在等待解释。 – SoonDead

回答

0

我已经改变了的drawImage和fillrectangle部分:

 g.DrawImage(res, p);    
     //left 
     g.FillRectangle(Brushes.Black, new Rectangle(0, 0, p.X, dest_size.Height)); 
     //right 
     g.FillRectangle(Brushes.Black, new Rectangle(p.X + act_size.Width, 0, p.X, dest_size.Height)); 
     //up 
     g.FillRectangle(Brushes.Black, new Rectangle(0, 0, dest_size.Width, p.Y)); 
     //down 
     g.FillRectangle(Brushes.Black, new Rectangle(0, p.Y + act_size.Width, dest_size.Width, p.Y)); 

,它似乎与我的测试情况下工作。不过,我不确定是什么导致了原始问题。