解决GDI+的图像质量的问题

最近在完成一个文章发布系统时需要给图片添加水印,采用GDI+的DrawString后发现图像质量非常糟糕,后来从其他地方找到如下代码,经过试验 图像质量大幅提高:
// 上传成功,加水印    
                        
                        
string  path = UploadFileDestination  +  UploadFileName;
                        System.Drawing.Image img 
=  System.Drawing.Image.FromFile(path);
            System.Drawing.Imaging.ImageFormat thisFormat 
=  img.RawFormat;

            
// Size newSize = NewSize(maxWidth, maxHeight, img.Width, img.Height);
            
// Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
            Graphics g  =  Graphics.FromImage(img);

            
//  设置画布的描绘质量
            g.CompositingQuality  =  CompositingQuality.HighQuality; 
            g.SmoothingMode 
=  SmoothingMode.HighQuality; 
            g.InterpolationMode 
=  InterpolationMode.HighQualityBicubic;

            g.DrawImage(img, 
0 0 , img.Width, img.Height);
                
            Font f 
=   new  Font( " Arial " , 9 );
                Brush b 
=   new  SolidBrush(Color.Black);
                Brush c 
=   new  SolidBrush(Color.White);
                
string  addText  =   " .com在线 " ;
                
                g.DrawString(addText, f, b, 
3 3 );
                g.DrawString(addText, f, c, 
2 2 );
                
                g.DrawString(addText, f, b, img.Width
- 140 , img.Height - 15 );
                g.DrawString(addText, f, c, img.Width
- 141 , img.Height - 16 );
                g.Dispose();        
            

            
//  以下代码为保存图片时,设置压缩质量
            EncoderParameters encoderParams  =   new  EncoderParameters();
            
long [] quality  =   new   long [ 1 ];
            quality[
0 =   100 ;

            EncoderParameter encoderParam 
=   new  EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[
0 =  encoderParam;

            
// 获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
            ImageCodecInfo[] arrayICI  =  ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI 
=   null ;
            
for  ( int  x  =   0 ; x  <  arrayICI.Length; x ++ )
            
{
                
if (arrayICI[x].FormatDescription.Equals("JPEG"))
                
{
                    jpegICI 
= arrayICI[x];//设置JPEG编码
                    break;
                }

            }


            
string  newPath  =  (UploadFileDestination + RNDFile()) + newext;

            
if  (jpegICI  !=   null )
            
{
                img.Save(newPath, jpegICI, encoderParams);
            }

            
else
            
{
                img.Save(newPath, thisFormat);
            }

            
            img.Dispose();
            
                        

                
// 保存加水印过后的图片,删除原始图片
                

                
if (File.Exists(path))
                
{
                    File.Delete(path);
                }
                            
                    
                        
                    
// 水印添加完成

你可能感兴趣的:(DI)