Split Png Aplha Channel

///
/// Split PNG file into two JPGs (RGB and alpha)
///
private voidSplitPngFileIntoRGBandAplha(string imagePath)
{
    try
    {
       // Open originalbitmap
       var bitmap = new Bitmap(imagePath);
       
       // Rectangle
       var rect = new Rectangle(0, 0,bitmap.Width, bitmap.Height);
       
       // Get RGB bitmap
       var bitmapInRgbFormat = bitmap.Clone(rect,PixelFormat.Format32bppRgb);
       
       // Read bitmapdata
       BitmapData bmData = bitmap.LockBits(rect,ImageLockMode.ReadOnly, bitmap.PixelFormat);
       
       // Prepare alphabitmap
       var alphaBitmap = new Bitmap(bmData.Width,bmData.Height, PixelFormat.Format32bppRgb);
       
       for(int y = 0; y <= bmData.Height -1; y++)
       {
          for (int x = 0; x <= bmData.Width -1; x++)
           {
              Color PixelColor =Color.FromArgb(Marshal.ReadInt32(bmData.Scan0, (bmData.Stride * y)+ (4 * x)));
              if (PixelColor.A > 0 & PixelColor.A <= 255)
              {
                 alphaBitmap.SetPixel(x, y,Color.FromArgb(PixelColor.A, PixelColor.A, PixelColor.A,PixelColor.A));
              }
              else
              {
                 alphaBitmap.SetPixel(x, y,Color.FromArgb(0, 0, 0,0));
              }
           }
       }
       
       bitmap.UnlockBits(bmData);
       
       // Prepare JPGformat
       ImageCodecInfo jgpEncoder =GetEncoder(ImageFormat.Jpeg);
       var encoder = Encoder.Quality;
       var encoderParameters = newEncoderParameters(1);
       var encoderParameter = newEncoderParameter(encoder, 100L);
       encoderParameters.Param[0] = encoderParameter;
       
       // Save RGB bitmap
      bitmapInRgbFormat.Save(imagePath.Replace("png", "jpg"), jgpEncoder, encoderParameters);
       
       // Save Alphabitmpa
       alphaBitmap.Save(imagePath.Replace(".png", "_alpha.jpg"), jgpEncoder,encoderParameters);
       
       bitmap.Dispose();
       bitmapInRgbFormat.Dispose();
       bitmap.Dispose();
       
       // Delete bitmap
       System.IO.File.Delete(imagePath);
    }
    catch(Exception e)
    {
       // Handleexception
    }
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值