C#画像の切り取り、2つの画像を合成して1つの画像を合成します

2683 ワード

 /// 
        ///     ,    ,        ,   _new,  1.png   1_new.png
        /// 
        ///          
        ///     x  
        ///     y  
        ///     
        ///     
        public static void caijianpic(String picPath,int x,int y,int width,int height)
        {
            //    
            String oldPath = picPath;
            //     
            String newPath = System.IO.Path.GetExtension(oldPath);
            //       ,       _new
            newPath = oldPath.Substring(0, oldPath.Length - newPath.Length) + "_new" + newPath;
            //      
            System.Drawing.Rectangle cropArea = new System.Drawing.Rectangle(x, y, width, height);
            //        
            //    
            System.Drawing.Image img = System.Drawing.Image.FromStream(new System.IO.MemoryStream(System.IO.File.ReadAllBytes(oldPath)));
            //        
            if ((img.Width < x + width) || img.Height < y + height)
            {
                MessageBox.Show("          !");
                img.Dispose();
                return;
            }
            //  Bitmap  
            System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(img);
            //    
            System.Drawing.Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
            //      
            bmpCrop.Save(newPath);
            //    
            img.Dispose(); bmpCrop.Dispose();
        }


        /// 
        ///               ,    ,  
        ///    ,          
        /// 
        ///       
        ///        
        public static Image CombinImage(string sourceImg, string destImg)
        {
            Image imgBack = System.Drawing.Image.FromFile(sourceImg); //     
            Image img = System.Drawing.Image.FromFile(destImg); //    
            //    System.Drawing.Image    System.Drawing.Graphics       
            Graphics g = Graphics.FromImage(imgBack);
            //g.DrawImage(imgBack, 0, 0, 148, 124); // g.DrawImage(imgBack, 0, 0,    ,    );
            g.FillRectangle(System.Drawing.Brushes.Black, -50, -50, (int)212, ((int)203));//           ,    ,     
            //g.DrawImage(img,          ,          ,    ,    );
            g.DrawImage(img, -50, -50, 212, 203);
            GC.Collect();
            string saveImagePath ="D:/     /sss.png";
            //save new image to file system.
            imgBack.Save(saveImagePath, ImageFormat.Png);
            return imgBack;
        }