2
我想對RGBa .png文件進行一些自動化處理,並輸出兩個jpeg文件:1,它只是RGB通道,另一個就是alpha通道,作爲灰度圖像。將PNG拆分爲RGB和Alpha通道
有沒有辦法在C#本身做到這一點?如果需要第三方庫,只要它是免費/開放源代碼就沒有問題,但我寧願直接使用GDI或其他軟件。
我想對RGBa .png文件進行一些自動化處理,並輸出兩個jpeg文件:1,它只是RGB通道,另一個就是alpha通道,作爲灰度圖像。將PNG拆分爲RGB和Alpha通道
有沒有辦法在C#本身做到這一點?如果需要第三方庫,只要它是免費/開放源代碼就沒有問題,但我寧願直接使用GDI或其他軟件。
選項 - 加載到位圖clone to get RGB only,手動grab bits with LockBits並提取alpha通道以從中創建新的灰度位圖。
// get RGB copy
var bitmapInRgbFormat = loadedBitmap.Clone(
new Rectangle(0, 0, loadedBitmap.Width, loadedBitmap.Height),
PixelFormat.Format32bppRgb)
這是我工作的代碼:
/// <summary>
/// Split PNG file into two JPGs (RGB and alpha)
/// </summary>
private void SplitPngFileIntoRGBandAplha(string imagePath)
{
try
{
// Open original bitmap
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 bitmap data
BitmapData bmData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);
// Prepare alpha bitmap
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 JPG format
ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
var encoder = Encoder.Quality;
var encoderParameters = new EncoderParameters(1);
var encoderParameter = new EncoderParameter(encoder, 100L);
encoderParameters.Param[0] = encoderParameter;
// Save RGB bitmap
bitmapInRgbFormat.Save(imagePath.Replace("png", "jpg"), jgpEncoder, encoderParameters);
// Save Alpha bitmpa
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)
{
// Handle exception
}
}
如何使用'ColorMatrix'用於獲取灰度圖像? – Magnus 2013-03-04 18:08:49
示例代碼請...我不知道該怎麼做。 – 2013-03-04 18:12:27