![](/img/trans.png)
[英]How to create a PNG image with the smallest size and good enough for web?
[英]How to create inverse png image?
我正在創建在我的基礎上繪制的png圖像,從基礎我可以保存一個png圖像,供您參考
Graphics g = e.Graphics;
....
g.DrawLine(pen, new Point(x, y), new Point(x1, y1));
.....
base.OnPaint(e);
using (var bmp = new Bitmap(500, 50))
{
base.DrawToBitmap(bmp, new Rectangle(0, 0, 500, 50));
bmp.Save(outPath);
}
這是單色透明圖像,現在我如何反轉這個圖像像png填充任何顏色和真實圖像部分應該是透明的,有可能嗎?
比特細節:透明會變得不透明,填充的地方會變得透明
如果您願意使用unsafe
代碼,有一種更快捷的方法:
private unsafe void Invert(Bitmap bmp)
{
int w = bmp.Width, h = bmp.Height;
BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
int* bytes = (int*)data.Scan0;
for ( int i = w*h-1; i >= 0; i-- )
bytes[i] = ~bytes[i];
bmp.UnlockBits(data);
}
請注意,這並不關心顏色,也會反轉這些顏色。 如果您希望使用特定顏色,則必須稍微修改代碼。
編輯 (感謝Thomas的記譜法)
public void ApplyInvert()
{
byte A, R, G, B;
Color pixelColor;
for (int y = 0; y < bitmapImage.Height; y++)
{
for (int x = 0; x < bitmapImage.Width; x++)
{
pixelColor = bitmapImage.GetPixel(x, y);
A = (byte)(255 - pixelColor.A);
R = pixelColor.R;
G = pixelColor.G;
B = pixelColor.B;
bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));
}
}
}
從這里: C#中的圖像處理:反轉圖像
對於任何想要快速方法來反轉位圖顏色而不使用不安全的人:
public static void BitmapInvertColors(Bitmap bitmapImage)
{
var bitmapRead = bitmapImage.LockBits(new Rectangle(0, 0, bitmapImage.Width, bitmapImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);
var bitmapLength = bitmapRead.Stride * bitmapRead.Height;
var bitmapBGRA = new byte[bitmapLength];
Marshal.Copy(bitmapRead.Scan0, bitmapBGRA, 0, bitmapLength);
bitmapImage.UnlockBits(bitmapRead);
for (int i = 0; i < bitmapLength; i += 4)
{
bitmapBGRA[i] = (byte)(255 - bitmapBGRA[i]);
bitmapBGRA[i + 1] = (byte)(255 - bitmapBGRA[i + 1]);
bitmapBGRA[i + 2] = (byte)(255 - bitmapBGRA[i + 2]);
// [i + 3] = ALPHA.
}
var bitmapWrite = bitmapImage.LockBits(new Rectangle(0, 0, bitmapImage.Width, bitmapImage.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb);
Marshal.Copy(bitmapBGRA, 0, bitmapWrite.Scan0, bitmapLength);
bitmapImage.UnlockBits(bitmapWrite);
}
Bitmap GetPixel和SetPixel非常慢,這種方法的工作原理是將Bitmap像素復制到一個字節數組中,然后在最終復制像素之前可以循環並更改。
當您說將透明部分反轉為顏色時,您是否將實際顏色存儲在剛剛設置為完全透明的PNG圖像中? 許多程序將通過從透明度中刪除顏色數據來優化png,因此您無法對其進行反轉。
顏色可以轉換為透明度但是透明度(沒有底層顏色)無法轉換為顏色。
如果幸運的話,你的PNG將不經過優化並且仍然保持原始顏色數據的完整性,但是如果你從用戶輸入中做到這一點,那么它將不適用於大部分情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.