Here are the examples of the csharp api System.Drawing.Bitmap.UnlockBits(System.Drawing.Imaging.BitmapData) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
794 Examples
19
Source : WebPFile.cs
with MIT License
from 0xC0000054
with MIT License
from 0xC0000054
internal static unsafe Bitmap Load(byte[] webpBytes)
{
if (webpBytes == null)
{
throw new ArgumentNullException(nameof(webpBytes));
}
WebPNative.ImageInfo imageInfo;
WebPNative.WebPGetImageInfo(webpBytes, out imageInfo);
if (imageInfo.hasAnimation)
{
throw new WebPException(Resources.AnimatedWebPNotSupported);
}
Bitmap image = null;
Bitmap temp = null;
try
{
temp = new Bitmap(imageInfo.width, imageInfo.height, PixelFormat.Format32bppArgb);
BitmapData bitmapData = temp.LockBits(new Rectangle(0, 0, imageInfo.width, imageInfo.height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
try
{
WebPNative.WebPLoad(webpBytes, bitmapData);
}
finally
{
temp.UnlockBits(bitmapData);
}
image = temp;
temp = null;
}
finally
{
if (temp != null)
{
temp.Dispose();
}
}
return image;
}
19
Source : BitmapToImageSourceConverter.cs
with GNU Affero General Public License v3.0
from 1thenikita
with GNU Affero General Public License v3.0
from 1thenikita
public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture)
{
if (!(value is Bitmap bitmap))
return null;
Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
bitmap.UnlockBits(bitmapData);
return BitmapSource.Create(bitmap.Width, bitmap.Height, bitmap.HorizontalResolution, bitmap.VerticalResolution, PixelFormats.Bgra32, null, bitmapData.Scan0, rect.Width * rect.Height * 4, bitmapData.Stride);
}
19
Source : ImageToModelContainer.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
private static Bitmap ConvolutionFilter(Bitmap sourceBitmap,
double[,] filterMatrix,
double factor = 1,
int bias = 0,
bool grayscale = false)
{
BitmapData sourceData =
sourceBitmap.LockBits(new Rectangle(0, 0,
sourceBitmap.Width, sourceBitmap.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppArgb);
byte[] pixelBuffer = new byte[sourceData.Stride *
sourceData.Height];
byte[] resultBuffer = new byte[sourceData.Stride *
sourceData.Height];
Marshal.Copy(sourceData.Scan0, pixelBuffer, 0,
pixelBuffer.Length);
sourceBitmap.UnlockBits(sourceData);
if (grayscale == true)
{
float rgb = 0;
for (int k = 0; k < pixelBuffer.Length; k += 4)
{
rgb = pixelBuffer[k] * 0.11f;
rgb += pixelBuffer[k + 1] * 0.59f;
rgb += pixelBuffer[k + 2] * 0.3f;
pixelBuffer[k] = (byte)rgb;
pixelBuffer[k + 1] = pixelBuffer[k];
pixelBuffer[k + 2] = pixelBuffer[k];
pixelBuffer[k + 3] = 255;
}
}
double blue = 0.0;
double green = 0.0;
double red = 0.0;
int filterWidth = filterMatrix.GetLength(1);
int filterHeight = filterMatrix.GetLength(0);
int filterOffset = (filterWidth - 1) / 2;
int calcOffset = 0;
int byteOffset = 0;
for (int offsetY = filterOffset; offsetY <
sourceBitmap.Height - filterOffset; offsetY++)
{
for (int offsetX = filterOffset; offsetX <
sourceBitmap.Width - filterOffset; offsetX++)
{
blue = 0;
green = 0;
red = 0;
byteOffset = offsetY *
sourceData.Stride +
offsetX * 4;
for (int filterY = -filterOffset;
filterY <= filterOffset; filterY++)
{
for (int filterX = -filterOffset;
filterX <= filterOffset; filterX++)
{
calcOffset = byteOffset +
(filterX * 4) +
(filterY * sourceData.Stride);
blue += (double)(pixelBuffer[calcOffset]) *
filterMatrix[filterY + filterOffset,
filterX + filterOffset];
green += (double)(pixelBuffer[calcOffset + 1]) *
filterMatrix[filterY + filterOffset,
filterX + filterOffset];
red += (double)(pixelBuffer[calcOffset + 2]) *
filterMatrix[filterY + filterOffset,
filterX + filterOffset];
}
}
blue = factor * blue + bias;
green = factor * green + bias;
red = factor * red + bias;
if (blue > 255)
{ blue = 255; }
else if (blue < 0)
{ blue = 0; }
if (green > 255)
{ green = 255; }
else if (green < 0)
{ green = 0; }
if (red > 255)
{ red = 255; }
else if (red < 0)
{ red = 0; }
resultBuffer[byteOffset] = (byte)(blue);
resultBuffer[byteOffset + 1] = (byte)(green);
resultBuffer[byteOffset + 2] = (byte)(red);
resultBuffer[byteOffset + 3] = 255;
}
}
Bitmap resultBitmap = new Bitmap(sourceBitmap.Width,
sourceBitmap.Height);
BitmapData resultData =
resultBitmap.LockBits(new Rectangle(0, 0,
resultBitmap.Width, resultBitmap.Height),
ImageLockMode.WriteOnly,
PixelFormat.Format32bppArgb);
Marshal.Copy(resultBuffer, 0, resultData.Scan0,
resultBuffer.Length);
resultBitmap.UnlockBits(resultData);
return resultBitmap;
}
19
Source : ImageToModelContainer.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
public static void doSomethingWithBitmapFast(System.Drawing.Bitmap bmp)
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect,
System.Drawing.Imaging.ImageLockMode.ReadOnly,
bmp.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = bmpData.Stride * bmp.Height;
byte[] rgbValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr,
rgbValues, 0, bytes);
byte red = 0;
byte green = 0;
byte blue = 0;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
//See the link above for an explanation
//of this calculation
int position = (y * bmpData.Stride) + (x * Image.GetPixelFormatSize(bmpData.PixelFormat) / 8);
blue = rgbValues[position];
green = rgbValues[position + 1];
red = rgbValues[position + 2];
Console.WriteLine("Fast: " + red + " "
+ green + " " + blue);
}
}
bmp.UnlockBits(bmpData);
}
19
Source : Cubemap.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
void Load(Resource[] resources)
{
// better performance: 2d array, 2d texture buffer
textureHandle = GL.GenTexture();
GL.BindTexture(TextureTarget.TextureCubeMap, textureHandle);
bool useMimMaps = false; // goes black if cubeMap uses mipmaps
// We will not upload mipmaps, so disable mipmapping (otherwise the texture will not appear).
// We can use GL.GenerateMipmaps() or GL.Ext.GenerateMipmaps() to create
// mipmaps automatically. In that case, use TextureMinFilter.LinearMipmapLinear to enable them.
GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMinFilter, (int)GetTextureMinFilter(useMimMaps));
GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMagFilter, (int)GetTextureMagFilter(useMimMaps));
GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapS, (int)GetTextureWrapMode());
GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapT, (int)GetTextureWrapMode());
GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapR, (int)GetTextureWrapMode());
// ???
//GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureLodBias, this.anisoLevel);
TextureTarget[] textureTargets = new TextureTarget[] {
TextureTarget.TextureCubeMapPositiveX,
TextureTarget.TextureCubeMapNegativeX,
TextureTarget.TextureCubeMapPositiveY,
TextureTarget.TextureCubeMapNegativeY,
TextureTarget.TextureCubeMapPositiveZ,
TextureTarget.TextureCubeMapNegativeZ,
};
for (int i = 0; i < 6; i++)
{
var textureTarget = textureTargets[i];
Bitmap bmp = new Bitmap(resources[i]);
BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
GL.TexImage2D(textureTarget, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0,
OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);
bmp.UnlockBits(bmp_data);
}
if (useMimMaps)
{
GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);
}
}
19
Source : Texture2D.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
void Load(Resource resource)
{
// better performance: 2d array, 2d texture buffer
textureHandle = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, textureHandle);
bool useMimMaps = true;
// We will not upload mipmaps, so disable mipmapping (otherwise the texture will not appear).
// We can use GL.GenerateMipmaps() or GL.Ext.GenerateMipmaps() to create
// mipmaps automatically. In that case, use TextureMinFilter.LinearMipmapLinear to enable them.
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)GetTextureMinFilter(useMimMaps));
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)GetTextureMagFilter(useMimMaps));
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)GetTextureWrapMode());
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)GetTextureWrapMode());
// ???
//GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureLodBias, this.anisoLevel);
Bitmap bmp = new Bitmap(resource);
BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0,
OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);
bmp.UnlockBits(bmp_data);
if (useMimMaps)
{
GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);
}
}
19
Source : ChannelFilter.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Apply(Image image)
{
if (_channel != ImageChannel.All)
{
uint mask;
int shift;
switch (_channel)
{
case ImageChannel.Red:
mask = 0x00FF0000;
shift = 16;
break;
case ImageChannel.Green:
mask = 0x0000FF00;
shift = 8;
break;
case ImageChannel.Blue:
mask = 0x000000FF;
shift = 0;
break;
case ImageChannel.Alpha:
mask = 0xFF000000;
shift = 24;
break;
default:
throw new ArgumentOutOfRangeException();
}
var bmp = image as Bitmap;
if (bmp != null)
{
var rect = new Rectangle(0, 0, image.Width, image.Height);
var bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
unsafe
{
var p = (byte*)bmpdata.Scan0;
for(var y = 0; y < bmp.Height; y++)
{
for(var x = 0; x < bmp.Width; x++)
{
var offset = y*bmpdata.Stride + x*4;
var data = (byte)(((*(int*) (p + offset)) & mask) >> shift);
p[offset + 0] = data;
p[offset + 1] = data;
p[offset + 2] = data;
p[offset + 3] = 255;
}
}
}
bmp.UnlockBits(bmpdata);
}
}
}
19
Source : TextureDecoder.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
internal static Image Decode(Texture texture, int level)
{
var width = texture.GetWidth(level);
var height = texture.GetHeight(level);
var data = texture.GetTextureData(level);
switch(texture.TextureType)
{
case TextureType.DXT1:
data = DXTDecoder.DecodeDXT1(data, (int)width, (int)height);
break;
case TextureType.DXT3:
data = DXTDecoder.DecodeDXT3(data, (int)width, (int)height);
break;
case TextureType.DXT5:
data = DXTDecoder.DecodeDXT5(data, (int)width, (int)height);
break;
case TextureType.A8R8G8B8:
// Nothing to do, the data is already in the format we want it to be
break;
case TextureType.L8:
{
var newData = new byte[data.Length*4];
for (int i = 0; i < data.Length; i++)
{
newData[i*4 + 0] = data[i];
newData[i*4 + 1] = data[i];
newData[i*4 + 2] = data[i];
newData[i*4 + 3] = 255;
}
data = newData;
}
break;
default:
throw new ArgumentOutOfRangeException();
}
var bmp = new Bitmap((int) width, (int) height, PixelFormat.Format32bppArgb);
var rect = new Rectangle(0, 0, (int) width, (int) height);
var bmpdata = bmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
Marshal.Copy(data, 0, bmpdata.Scan0, (int) width*(int) height*4);
bmp.UnlockBits(bmpdata);
return bmp;
}
19
Source : TextureEncoder.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
internal static void Encode(Texture texture, Image image, int level)
{
var width = texture.GetWidth(level);
var height = texture.GetHeight(level);
var data = new byte[width * height * 4]; // R G B A
var bitmap = new Bitmap((int)width, (int)height);
Graphics g = Graphics.FromImage(bitmap);
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
g.DrawImage(image, 0, 0, (int)width, (int)height);
g.Dispose();
var rect = new Rectangle(0, 0, (int) width, (int) height);
BitmapData bmpdata = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
if (texture.TextureType == TextureType.A8R8G8B8)
{
Marshal.Copy(bmpdata.Scan0, data, 0, (int) width*(int) height*4);
}
else if (texture.TextureType == TextureType.L8)
{
var newData = new byte[width * height];
// Convert to L8
unsafe
{
var p = (byte*)bmpdata.Scan0;
for (var y = 0; y < bitmap.Height; y++)
{
for (var x = 0; x < bitmap.Width; x++)
{
var offset = y * bmpdata.Stride + x * 4;
var dataOffset = y * width + x;
newData[dataOffset] = (byte)((p[offset + 2] + p[offset + 1] + p[offset + 0])/3);
}
}
}
data = newData;
}
else
{
// Convert from the B G R A format stored by GDI+ to R G B A
unsafe
{
var p = (byte*)bmpdata.Scan0;
for (var y = 0; y < bitmap.Height; y++)
{
for (var x = 0; x < bitmap.Width; x++)
{
var offset = y * bmpdata.Stride + x * 4;
var dataOffset = y * width * 4 + x * 4;
data[dataOffset + 0] = p[offset + 2]; // R
data[dataOffset + 1] = p[offset + 1]; // G
data[dataOffset + 2] = p[offset + 0]; // B
data[dataOffset + 3] = p[offset + 3]; // A
}
}
}
}
bitmap.UnlockBits(bmpdata);
bitmap.Dispose();
switch (texture.TextureType)
{
case TextureType.DXT1:
data = DXTEncoder.EncodeDXT1(data, (int) width, (int) height);
break;
case TextureType.DXT3:
data = DXTEncoder.EncodeDXT3(data, (int) width, (int) height);
break;
case TextureType.DXT5:
data = DXTEncoder.EncodeDXT5(data, (int) width, (int) height);
break;
case TextureType.A8R8G8B8:
case TextureType.L8:
// Nothing to do
break;
default:
throw new ArgumentOutOfRangeException();
}
texture.SetTextureData(level, data);
}
19
Source : MainWindow.xaml.cs
with MIT License
from ahuchjm
with MIT License
from ahuchjm
List<System.Drawing.Point> FindPicture(string subPic, string parPic, System.Drawing.Rectangle searchRect, byte errorRange, double matchRate = 0.9, bool isFindAll = false)
{
List<System.Drawing.Point> ListPoint = new List<System.Drawing.Point>();
var subBitmap = new Bitmap(subPic);
var parBitmap = new Bitmap(parPic);
int subWidth = subBitmap.Width;
int subHeight = subBitmap.Height;
int parWidth = parBitmap.Width;
int parHeight = parBitmap.Height;
if (searchRect.IsEmpty)
{
searchRect = new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height);
}
var searchLeftTop = searchRect.Location;
var searchSize = searchRect.Size;
System.Drawing.Color startPixelColor = subBitmap.GetPixel(0, 0);
var subData = subBitmap.LockBits(new System.Drawing.Rectangle(0, 0, subBitmap.Width, subBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
var parData = parBitmap.LockBits(new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
var byteArrarySub = new byte[subData.Stride * subData.Height];
var byteArraryPar = new byte[parData.Stride * parData.Height];
Marshal.Copy(subData.Scan0, byteArrarySub, 0, subData.Stride * subData.Height);
Marshal.Copy(parData.Scan0, byteArraryPar, 0, parData.Stride * parData.Height);
var iMax = searchLeftTop.Y + searchSize.Height - subData.Height;//行
var jMax = searchLeftTop.X + searchSize.Width - subData.Width;//列
int smallOffsetX = 0, smallOffsetY = 0;
int smallStartX = 0, smallStartY = 0;
int pointX = -1; int pointY = -1;
for (int i = searchLeftTop.Y; i < iMax; i++)
{
for (int j = searchLeftTop.X; j < jMax; j++)
{
//大图x,y坐标处的颜色值
int x = j, y = i;
int parIndex = i * parWidth * 4 + j * 4;
var colorBig = System.Drawing.Color.FromArgb(byteArraryPar[parIndex + 3], byteArraryPar[parIndex + 2], byteArraryPar[parIndex + 1], byteArraryPar[parIndex]);
;
if (ColorAEqualColorB(colorBig, startPixelColor, errorRange))
{
smallStartX = x - smallOffsetX;//待找的图X坐标
smallStartY = y - smallOffsetY;//待找的图Y坐标
int sum = 0;//所有需要比对的有效点
int matchNum = 0;//成功匹配的点
for (int m = 0; m < subHeight; m++)
{
for (int n = 0; n < subWidth; n++)
{
int x1 = n, y1 = m;
int subIndex = m * subWidth * 4 + n * 4;
var color = System.Drawing.Color.FromArgb(byteArrarySub[subIndex + 3], byteArrarySub[subIndex + 2], byteArrarySub[subIndex + 1], byteArrarySub[subIndex]);
sum++;
int x2 = smallStartX + x1, y2 = smallStartY + y1;
int parReleativeIndex = y2 * parWidth * 4 + x2 * 4;//比对大图对应的像素点的颜色
var colorPixel = System.Drawing.Color.FromArgb(byteArraryPar[parReleativeIndex + 3], byteArraryPar[parReleativeIndex + 2], byteArraryPar[parReleativeIndex + 1], byteArraryPar[parReleativeIndex]);
if (ColorAEqualColorB(colorPixel, color, errorRange))
{
matchNum++;
}
}
}
if ((double)matchNum / sum >= matchRate)
{
Console.WriteLine((double)matchNum / sum);
pointX = smallStartX + (int)(subWidth / 2.0);
pointY = smallStartY + (int)(subHeight / 2.0);
var point = new System.Drawing.Point(pointX, pointY);
if (!ListContainsPoint(ListPoint, point, 10))
{
ListPoint.Add(point);
}
if (!isFindAll)
{
goto FIND_END;
}
}
}
//小图x1,y1坐标处的颜色值
}
}
FIND_END:
subBitmap.UnlockBits(subData);
parBitmap.UnlockBits(parData);
subBitmap.Dispose();
parBitmap.Dispose();
GC.Collect();
return ListPoint;
}
19
Source : MainWindow.xaml.cs
with MIT License
from ahuchjm
with MIT License
from ahuchjm
List<NumBody> FindText(string subPic, string parPic, System.Drawing.Rectangle searchRect, byte errorRange, double matchRate = 0.9, bool isFindAll = false)
{
List<NumBody> ListPoint = new List<NumBody>();
var subBitmap = new Bitmap(subPic);
var parBitmap = new Bitmap(parPic);
int subWidth = subBitmap.Width;
int subHeight = subBitmap.Height;
int parWidth = parBitmap.Width;
int parHeight = parBitmap.Height;
var bgColor = subBitmap.GetPixel(0, 0);//背景红色
if (searchRect.IsEmpty)
{
searchRect = new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height);
}
var searchLeftTop = searchRect.Location;
var searchSize = searchRect.Size;
var subData = subBitmap.LockBits(new System.Drawing.Rectangle(0, 0, subBitmap.Width, subBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
var parData = parBitmap.LockBits(new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
var byteArrarySub = new byte[subData.Stride * subData.Height];
var byteArraryPar = new byte[parData.Stride * parData.Height];
Marshal.Copy(subData.Scan0, byteArrarySub, 0, subData.Stride * subData.Height);
Marshal.Copy(parData.Scan0, byteArraryPar, 0, parData.Stride * parData.Height);
var iMax = searchLeftTop.Y + searchSize.Height - subData.Height;//行
var jMax = searchLeftTop.X + searchSize.Width - subData.Width;//列
System.Drawing.Color startPixelColor = System.Drawing.Color.FromArgb(0, 0, 0);
int smallOffsetX = 0, smallOffsetY = 0;
int smallStartX = 0, smallStartY = 0;
int pointX = -1; int pointY = -1;
for (int m = 0; m < subHeight; m++)
{
for (int n = 0; n < subWidth; n++)
{
smallOffsetX = n;
smallOffsetY = m;
int subIndex = m * subWidth * 4 + n * 4;
var color = System.Drawing.Color.FromArgb(byteArrarySub[subIndex + 3], byteArrarySub[subIndex + 2], byteArrarySub[subIndex + 1], byteArrarySub[subIndex]);
if (!ColorAEqualColorB(color, bgColor, errorRange))
{
startPixelColor = color;
goto END;
}
}
}
END:
for (int i = searchLeftTop.Y; i < iMax; i++)
{
for (int j = searchLeftTop.X; j < jMax; j++)
{
//大图x,y坐标处的颜色值
int x = j, y = i;
int parIndex = i * parWidth * 4 + j * 4;
var colorBig = System.Drawing.Color.FromArgb(byteArraryPar[parIndex + 3], byteArraryPar[parIndex + 2], byteArraryPar[parIndex + 1], byteArraryPar[parIndex]);
;
List<System.Drawing.Point> myListPoint = new List<System.Drawing.Point>();
if (ColorAEqualColorB(colorBig, startPixelColor, errorRange))
{
smallStartX = x - smallOffsetX;//待找的图X坐标
smallStartY = y - smallOffsetY;//待找的图Y坐标
int sum = 0;//所有需要比对的有效点
int matchNum = 0;//成功匹配的点
for (int m = 0; m < subHeight; m++)
{
for (int n = 0; n < subWidth; n++)
{
int x1 = n, y1 = m;
int subIndex = m * subWidth * 4 + n * 4;
var color = System.Drawing.Color.FromArgb(byteArrarySub[subIndex + 3], byteArrarySub[subIndex + 2], byteArrarySub[subIndex + 1], byteArrarySub[subIndex]);
if (color != bgColor)
{
sum++;
int x2 = smallStartX + x1, y2 = smallStartY + y1;
int parReleativeIndex = y2 * parWidth * 4 + x2 * 4;//比对大图对应的像素点的颜色
var colorPixel = System.Drawing.Color.FromArgb(byteArraryPar[parReleativeIndex + 3], byteArraryPar[parReleativeIndex + 2], byteArraryPar[parReleativeIndex + 1], byteArraryPar[parReleativeIndex]);
if (ColorAEqualColorB(colorPixel, color, errorRange))
{
matchNum++;
}
myListPoint.Add(new System.Drawing.Point(x2, y2));
}
}
}
double rate = (double)matchNum / sum;
if (rate>= matchRate)
{
Console.WriteLine((double)matchNum / sum);
pointX = smallStartX + (int)(subWidth / 2.0);
pointY = smallStartY + (int)(subHeight / 2.0);
var point = new System.Drawing.Point(pointX, pointY);
if (!ListTextBodyContainsPoint(ListPoint, point, 1))
{
ListPoint.Add(new NumBody() { point = point, matchNum = matchNum,matchSum=sum, matchRate = rate, bodyCollectionPoint = myListPoint });
}
SearchNumbersByMatchNum(ref ListPoint);
if (!isFindAll)
{
goto FIND_END;
}
}
}
//小图x1,y1坐标处的颜色值
}
}
FIND_END:
subBitmap.UnlockBits(subData);
parBitmap.UnlockBits(parData);
subBitmap.Dispose();
parBitmap.Dispose();
GC.Collect();
return ListPoint;
}
19
Source : MainWindow.xaml.cs
with MIT License
from ahuchjm
with MIT License
from ahuchjm
System.Drawing.Point FindColor(string parPic, string searchColor, System.Drawing.Rectangle searchRect, byte errorRange = 10)
{
var colorX = System.Drawing.ColorTranslator.FromHtml(searchColor);
var parBitmap = new Bitmap(parPic);
var parData = parBitmap.LockBits(new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
var byteArraryPar = new byte[parData.Stride * parData.Height];
Marshal.Copy(parData.Scan0, byteArraryPar, 0, parData.Stride * parData.Height);
if (searchRect.IsEmpty)
{
searchRect = new System.Drawing.Rectangle(0, 0, parBitmap.Width, parBitmap.Height);
}
var searchLeftTop = searchRect.Location;
var searchSize = searchRect.Size;
var iMax = searchLeftTop.Y + searchSize.Height;//行
var jMax = searchLeftTop.X + searchSize.Width;//列
int pointX = -1; int pointY = -1;
for (int m = searchRect.Y; m < iMax; m++)
{
for (int n = searchRect.X; n < jMax; n++)
{
int index = m * parBitmap.Width * 4 + n * 4;
var color = System.Drawing.Color.FromArgb(byteArraryPar[index + 3], byteArraryPar[index + 2], byteArraryPar[index + 1], byteArraryPar[index]);
if (ColorAEqualColorB(color, colorX, errorRange))
{
pointX = n;
pointY = m;
goto END;
}
}
}
END:
parBitmap.UnlockBits(parData);
return new System.Drawing.Point(pointX, pointY);
}
19
Source : Bitmap.cs
with Mozilla Public License 2.0
from ahyahy
with Mozilla Public License 2.0
from ahyahy
public void UnlockBits(osf.BitmapData p1)
{
M_Bitmap.UnlockBits(p1.M_BitmapData);
}
19
Source : ImageColorsConverter.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public unsafe Image SaveImageWithNewColorTable(Image image)
{
Bitmap bitmap = null;
Bitmap bitmap2 = null;
Graphics graphics = null;
BitmapData bitmapdata = null;
BitmapData data2 = null;
if (this._imgColors > 0x100)
{
this._imgColors = 0x100;
}
if (this._imgColors < 2)
{
this._imgColors = 2;
}
int width = image.Width;
int height = image.Height;
try
{
byte* numPtr;
byte* numPtr2;
bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
bitmap.Palette = this.pal;
bitmap2 = new Bitmap(width, height, PixelFormat.Format32bppArgb);
graphics = Graphics.FromImage(bitmap2);
graphics.PageUnit = GraphicsUnit.Pixel;
graphics.DrawImage(image, 0, 0, width, height);
Rectangle rect = new Rectangle(0, 0, width, height);
bitmapdata = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
data2 = bitmap2.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
IntPtr ptr = bitmapdata.Scan0;
IntPtr ptr2 = data2.Scan0;
if (bitmapdata.Stride > 0)
{
numPtr = (byte*)ptr.ToPointer();
}
else
{
numPtr = (byte*)ptr.ToPointer() + (bitmapdata.Stride * (height - 1));
}
if (data2.Stride > 0)
{
numPtr2 = (byte*)ptr2.ToPointer();
}
else
{
numPtr2 = (byte*)ptr2.ToPointer() + (data2.Stride * (height - 1));
}
uint num3 = (uint)Math.Abs(bitmapdata.Stride);
uint num4 = (uint)Math.Abs(data2.Stride);
for (uint i = 0; i < height; i++)
{
PixelData* dataPtr = (PixelData*)(numPtr2 + (i * num4));
byte* numPtr3 = numPtr + (i * num3);
for (uint j = 0; j < width; j++)
{
double num7 = ((dataPtr->red * 0.299) + (dataPtr->green * 0.587)) + (dataPtr->blue * 0.114);
numPtr3[0] = (byte)(((num7 * (this._imgColors - 1)) / 255.0) + 0.5);
dataPtr++;
numPtr3++;
}
}
bitmap.UnlockBits(bitmapdata);
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
finally
{
bitmap2.UnlockBits(data2);
bitmap2.Dispose();
graphics.Dispose();
bitmapdata = null;
data2 = null;
}
return bitmap;
}
19
Source : ImageCompression.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static void SaveGrayScale(
Image image,
string filename,
uint nColors,
bool fTransparent
)
{
// GIF codec supports 256 colors maximum, monochrome minimum.
if (nColors > 256)
nColors = 256;
if (nColors < 2)
nColors = 2;
// Make a new 8-BPP indexed bitmap that is the same size as the source image.
int Width = image.Width;
int Height = image.Height;
// Always use PixelFormat8bppIndexed because that is the color
// table-based interface to the GIF codec.
Bitmap bitmap = new Bitmap(Width,
Height,
PixelFormat.Format8bppIndexed);
// Create a color palette big enough to hold the colors you want.
ColorPalette pal = GetColorPalette(nColors);
// Initialize a new color table with entries that are determined
// by some optimal palette-finding algorithm; for demonstration
// purposes, use a grayscale.
for (uint i = 0; i < nColors; i++)
{
uint Alpha = 0xFF; // Colors are opaque.
uint Intensity = i * 0xFF / (nColors - 1); // Even distribution.
// The GIF encoder makes the first entry in the palette
// that has a ZERO alpha the transparent color in the GIF.
// Pick the first one arbitrarily, for demonstration purposes.
if (i == 0 && fTransparent) // Make this color index...
Alpha = 0; // Transparent
// Create a gray scale for demonstration purposes.
// Otherwise, use your favorite color reduction algorithm
// and an optimum palette for that algorithm generated here.
// For example, a color histogram, or a median cut palette.
pal.Entries[i] = Color.FromArgb((int)Alpha,
(int)Intensity,
(int)Intensity,
(int)Intensity);
}
// Set the palette into the new Bitmap object.
bitmap.Palette = pal;
// Use GetPixel below to pull out the color data of Image.
// Because GetPixel isn't defined on an Image, make a copy
// in a Bitmap instead. Make a new Bitmap that is the same size as the
// image that you want to export. Or, try to
// interpret the native pixel format of the image by using a LockBits
// call. Use PixelFormat32BppARGB so you can wrap a Graphics
// around it.
Bitmap BmpCopy = new Bitmap(Width,
Height,
PixelFormat.Format32bppArgb);
{
Graphics g = Graphics.FromImage(BmpCopy);
g.PageUnit = GraphicsUnit.Pixel;
// Transfer the Image to the Bitmap
g.DrawImage(image, 0, 0, Width, Height);
// g goes out of scope and is marked for garbage collection.
// Force it, just to keep things clean.
g.Dispose();
}
// Lock a rectangular portion of the bitmap for writing.
BitmapData bitmapData;
Rectangle rect = new Rectangle(0, 0, Width, Height);
bitmapData = bitmap.LockBits(
rect,
ImageLockMode.WriteOnly,
PixelFormat.Format8bppIndexed);
// Write to the temporary buffer that is provided by LockBits.
// Copy the pixels from the source image in this loop.
// Because you want an index, convert RGB to the appropriate
// palette index here.
IntPtr pixels = bitmapData.Scan0;
unsafe
{
// Get the pointer to the image bits.
// This is the unsafe operation.
byte* pBits;
if (bitmapData.Stride > 0)
pBits = (byte*)pixels.ToPointer();
else
// If the Stide is negative, Scan0 points to the last
// scanline in the buffer. To normalize the loop, obtain
// a pointer to the front of the buffer that is located
// (Height-1) scanlines previous.
pBits = (byte*)pixels.ToPointer() + bitmapData.Stride * (Height - 1);
uint stride = (uint)Math.Abs(bitmapData.Stride);
for (uint row = 0; row < Height; ++row)
{
for (uint col = 0; col < Width; ++col)
{
// Map palette indexes for a gray scale.
// If you use some other technique to color convert,
// put your favorite color reduction algorithm here.
Color pixel; // The source pixel.
// The destination pixel.
// The pointer to the color index byte of the
// destination; this real pointer causes this
// code to be considered unsafe.
byte* p8bppPixel = pBits + row * stride + col;
pixel = BmpCopy.GetPixel((int)col, (int)row);
// Use luminance/chrominance conversion to get grayscale.
// Basically, turn the image into black and white TV.
// Do not calculate Cr or Cb because you
// discard the color anyway.
// Y = Red * 0.299 + Green * 0.587 + Blue * 0.114
// This expression is best as integer math for performance,
// however, because GetPixel listed earlier is the slowest
// part of this loop, the expression is left as
// floating point for clarity.
double luminance = (pixel.R * 0.299) +
(pixel.G * 0.587) +
(pixel.B * 0.114);
// Gray scale is an intensity map from black to white.
// Compute the index to the grayscale entry that
// approximates the luminance, and then round the index.
// Also, constrain the index choices by the number of
// colors to do, and then set that pixel's index to the
// byte value.
*p8bppPixel = (byte)(luminance * (nColors - 1) / 255 + 0.5);
} /* end loop for col */
} /* end loop for row */
} /* end unsafe */
// To commit the changes, unlock the portion of the bitmap.
bitmap.UnlockBits(bitmapData);
bitmap.Save(filename, ImageFormat.Png);
// Bitmap goes out of scope here and is also marked for
// garbage collection.
// Pal is referenced by bitmap and goes away.
// BmpCopy goes out of scope here and is marked for garbage
// collection. Force it, because it is probably quite large.
// The same applies to bitmap.
BmpCopy.Dispose();
bitmap.Dispose();
}
19
Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static Image GrayScaleImage(Image srcImage)
{
try
{
int width = srcImage.Width;
int height = srcImage.Height;
Rectangle rect = new Rectangle(0, 0, width, height);
Bitmap newBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed) { Palette = GrayScalePalette };
using (Bitmap srcBmp = new Bitmap(width, height, PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(srcBmp))
g.DrawImage(srcImage, 0, 0);
BitmapData srcData = srcBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
BitmapData newData = newBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
Debug.replacedert(srcData.Stride > 0);
Debug.replacedert(newData.Stride > 0);
int srcStride = srcData.Stride;
int newStride = newData.Stride;
unsafe
{
byte* pSrc = (byte*)srcData.Scan0.ToPointer();
byte* pNew = (byte*)newData.Scan0.ToPointer();
Argb* ps;
byte* pn;
for (int y = 0; y < height; ++y)
{
ps = (Argb*)(pSrc + (srcStride * y));
pn = (byte*)(pNew + (newStride * y));
for (int x = 0; x < width; ++x)
{
Argb color = *ps;
*pn = (byte)((color.red * 0.299) + (color.green * 0.587) + (color.blue * 0.114) + 0.5);
++ps;
++pn;
}
}
}
srcBmp.UnlockBits(srcData);
newBmp.UnlockBits(newData);
}
return newBmp;
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
}
19
Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static Image TransparentColorImage(Image bgImage, Image srcImage, float ratio)
{
Debug.replacedert(srcImage != null && srcImage.PixelFormat == PixelFormat.Format16bppRgb555);
Debug.replacedert(bgImage != null && bgImage.PixelFormat == PixelFormat.Format16bppRgb555);
Debug.replacedert(srcImage.Width == bgImage.Width && srcImage.Height == bgImage.Height);
Debug.replacedert(0 < ratio && ratio < 1);
Image newImage = null;
try
{
int width = bgImage.Width;
int height = bgImage.Height;
Rectangle rect = new Rectangle(0, 0, width, height);
long diffMax = (int)(width * height * ratio);
long diffCount = 0;
Bitmap newBmp = new Bitmap(width, height, PixelFormat.Format16bppArgb1555);
using (Bitmap srcBmp = new Bitmap(srcImage))
using (Bitmap bgBmp = new Bitmap(bgImage))
{
BitmapData srcData = srcBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format16bppRgb555);
BitmapData bgData = bgBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format16bppRgb555);
BitmapData newData = newBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format16bppArgb1555);
Debug.replacedert(srcData.Stride == bgData.Stride && srcData.Stride == newData.Stride);
int stride = srcData.Stride;
unsafe
{
byte* pSrc = (byte*)srcData.Scan0.ToPointer();
byte* pBkg = (byte*)bgData.Scan0.ToPointer();
byte* pNew = (byte*)newData.Scan0.ToPointer();
ushort* ps, pg, pn;
for (int y = 0; y < height; ++y)
{
ps = (ushort*)(pSrc + (stride * y));
pg = (ushort*)(pBkg+ (stride * y));
pn = (ushort*)(pNew + (stride * y));
for (int x = 0; x < width; ++x)
{
//if (0 == *ps)
// *pn = (ushort)(*ps | 0x8000);
//else
*pn = (ushort)((*pg == *ps) ? 0 : (*ps | 0x8000));
++ps;
++pg;
++pn;
diffCount += ((*pg == *ps) ? 0 : 1);
}
if (diffCount >= diffMax)
break;
}
}
srcBmp.UnlockBits(srcData);
bgBmp.UnlockBits(bgData);
newBmp.UnlockBits(newData);
}
if (diffCount < diffMax)
{
//newBmp.MakeTransparent(Color.Empty);
newImage = newBmp;
}
else
{
newBmp.Dispose();
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return newImage;
}
19
Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static byte[] XorGrayscaleImage(Image bgImage, Image srcImage, float ratio)
{
Debug.replacedert(srcImage != null && srcImage.PixelFormat == PixelFormat.Format8bppIndexed);
Debug.replacedert(bgImage != null && bgImage.PixelFormat == PixelFormat.Format8bppIndexed);
Debug.replacedert(srcImage.Width == bgImage.Width && srcImage.Height == bgImage.Height);
Debug.replacedert(0 < ratio && ratio < 1);
byte[] bsXor = null;
try
{
int width = bgImage.Width;
int height = bgImage.Height;
Rectangle rect = new Rectangle(0, 0, width, height);
long diffMax = (int)(width * height * ratio);
long diffCount = 0;
using (Bitmap srcBmp = new Bitmap(srcImage))
using (Bitmap bkgBmp = new Bitmap(bgImage))
using (Bitmap newBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed))
{
BitmapData srcData = srcBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
BitmapData bkgData = bkgBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
BitmapData newData = newBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
Debug.replacedert(srcData.Stride == bkgData.Stride && srcData.Stride == newData.Stride);
Debug.replacedert(srcData.Stride % 4 == 0);
int stride = srcData.Stride;
unsafe
{
byte* pSrc = (byte*)srcData.Scan0.ToPointer();
byte* pBkg = (byte*)bkgData.Scan0.ToPointer();
byte* pNew = (byte*)newData.Scan0.ToPointer();
uint* ps, pg, pn;
for (int y = 0; y < height; ++y)
{
ps = (uint*)(pSrc + (stride * y));
pg = (uint*)(pBkg + (stride * y));
pn = (uint*)(pNew + (stride * y));
for (int x = 0; x < width; x += 4)
{
*pn = *pg ^ *ps;
++ps;
++pg;
++pn;
diffCount += ((*pg == *ps) ? 0 : 4);
}
if (diffCount >= diffMax)
break;
}
}
if (diffCount < diffMax)
{
bsXor = new byte[newData.Stride * newData.Height];
Marshal.Copy(newData.Scan0, bsXor, 0, bsXor.Length);
}
srcBmp.UnlockBits(srcData);
bkgBmp.UnlockBits(bkgData);
newBmp.UnlockBits(newData);
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return bsXor;
}
19
Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static Image CombineGrayscaleXor(Image srcImage, byte[] bsXor)
{
Debug.replacedert(srcImage != null && srcImage.PixelFormat == PixelFormat.Format8bppIndexed);
Image newImage = null;
try
{
int width = srcImage.Width;
int height = srcImage.Height;
Rectangle rect = new Rectangle(0, 0, width, height);
Bitmap srcBmp = new Bitmap(srcImage);
srcBmp.Palette = GrayScalePalette;
BitmapData srcData = srcBmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
Debug.replacedert(srcData.Stride * srcData.Height == bsXor.Length);
Debug.replacedert(srcData.Stride % 4 == 0);
int stride = srcData.Stride;
unsafe
{
fixed (byte* pXor = bsXor)
{
byte* pSrc = (byte*)srcData.Scan0.ToPointer();
uint* ps, px;
for (int y = 0; y < height; ++y)
{
ps = (uint*)(pSrc + (stride * y));
px = (uint*)(pXor + (stride * y));
for (int x = 0; x < width; x += 4)
{
*ps = (*ps ^ *px);
++ps;
++px;
}
}
}
}
srcBmp.UnlockBits(srcData);
newImage = srcBmp;
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return newImage;
}
19
Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static Image TransparentImage8(Image bgImage, Image srcImage, float ratio)
{
Debug.replacedert(srcImage != null && srcImage.PixelFormat == PixelFormat.Format8bppIndexed);
Debug.replacedert(bgImage != null && bgImage.PixelFormat == PixelFormat.Format8bppIndexed);
Debug.replacedert(srcImage.Width == bgImage.Width && srcImage.Height == bgImage.Height);
Debug.replacedert(0 < ratio && ratio < 1);
Image newImage = null;
try
{
int width = bgImage.Width;
int height = bgImage.Height;
Rectangle rect = new Rectangle(0, 0, width, height);
long diffMax = (int)(width * height * ratio);
long diffCount = 0;
Bitmap newBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
newBmp.Palette = srcImage.Palette;
using (Bitmap srcBmp = new Bitmap(srcImage))
using (Bitmap bkgBmp = new Bitmap(bgImage))
{
BitmapData srcData = srcBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
BitmapData bkgData = bkgBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
BitmapData newData = newBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
unsafe
{
byte* pSrc = (byte*)srcData.Scan0.ToPointer();
byte* pBkg = (byte*)bkgData.Scan0.ToPointer();
byte* pNew = (byte*)newData.Scan0.ToPointer();
byte* ps, pg, pn;
for (int y = 0; y < height; ++y)
{
ps = pSrc + (y * srcData.Stride);
pg = pBkg + (y * bkgData.Stride);
pn = pNew + (y * newData.Stride);
for (int x = 0; x < width; ++x)
{
if (0 == *ps)
*pn = 0xFF;
else
*pn = (byte)((*pg == *ps) ? 0 : *ps);
++ps;
++pg;
++pn;
diffCount += ((*pg == *ps) ? 0 : 1);
}
if (diffCount >= diffMax)
break;
}
}
srcBmp.UnlockBits(srcData);
bkgBmp.UnlockBits(bkgData);
newBmp.UnlockBits(newData);
}
if (diffCount < diffMax)
{
newBmp.MakeTransparent(Color.Empty);
newImage = newBmp;
}
else
{
newBmp.Dispose();
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return newImage;
}
19
Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static Image _TransparentImage8(Image bgImage, Image srcImage, float ratio, out bool transparent)
{
Debug.replacedert(srcImage != null && srcImage.PixelFormat == PixelFormat.Format8bppIndexed);
Debug.replacedert(bgImage != null && bgImage.PixelFormat == PixelFormat.Format8bppIndexed);
Debug.replacedert(srcImage.Width == bgImage.Width && srcImage.Height == bgImage.Height);
Debug.replacedert(0 < ratio && ratio < 1);
transparent = false;
Image newImage = srcImage;
try
{
int width = bgImage.Width;
int height = bgImage.Height;
Rectangle rect = new Rectangle(0, 0, width, height);
long diffMax = (int)(width * height * ratio);
long diffCount = 0;
Bitmap newBmp = new Bitmap(srcImage);
using (Bitmap bgBmp = new Bitmap(bgImage))
{
BitmapData bgData = bgBmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
BitmapData newData = newBmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
unsafe
{
byte* pBkg = (byte*)bgData.Scan0.ToPointer();
byte* pNew = (byte*)newData.Scan0.ToPointer();
byte* pg = pBkg;
byte* pn = pNew;
for (int y = 0; y < height; ++y)
{
pg = pBkg + (y * bgData.Stride);
pn = pNew + (y * newData.Stride);
for (int x = 0; x < width; ++x)
{
diffCount += ((*pg == *pn) ? 0 : 1);
if (0 == *pn)
*pn = 1;
else
*pn = (byte)((*pg == *pn) ? 0 : *pn);
++pg;
++pn;
}
if (diffCount >= diffMax)
break;
}
}
newBmp.UnlockBits(newData);
bgBmp.UnlockBits(bgData);
}
if (diffCount < diffMax)
{
newBmp.MakeTransparent(Color.Empty);
newImage = newBmp;
transparent = true;
}
else
{
newBmp.Dispose();
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return newImage;
}
19
Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static Bitmap GrayScaleBitmap(Image img)
{
Bitmap newImage = null;
try
{
int nColors = 8;
int width = img.Width;
int height = img.Height;
Rectangle rect = new Rectangle(0, 0, width, height);
Bitmap newBitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
newBitmap.Palette = GrayScalePalette;
using (Bitmap srcBitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(srcBitmap))
{
g.PageUnit = GraphicsUnit.Pixel;
g.DrawImage(img, 0, 0);
}
var srcData = srcBitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
var newData = newBitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
unsafe
{
int srcStride = Math.Abs(srcData.Stride);
int newStride = Math.Abs(newData.Stride);
byte* pSrc = (byte*)srcData.Scan0.ToPointer() + ((srcData.Stride > 0) ? 0 : (srcData.Stride * (height - 1)));
byte* pNew = newData.Stride > 0 ? (byte*)newData.Scan0.ToPointer() : (byte*)newData.Scan0.ToPointer() + (newData.Stride * (height - 1));
PixelData* ps;
byte* pn;
for (uint y = 0; y < height; y++)
{
ps = (PixelData*)(pSrc + (srcStride * y));
pn = pNew + (newStride * y);
for (uint x = 0; x < width; x++)
{
double dv = ((ps->red * 0.299) + (ps->green * 0.587)) + (ps->blue * 0.114);
pn[0] = (byte)(((dv * (nColors - 1)) / 255.0) + 0.5);
++ps;
++pn;
}
}
}
srcBitmap.UnlockBits(srcData);
newBitmap.UnlockBits(newData);
srcData = null;
newData = null;
}
newImage = newBitmap;
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return newImage;
}
19
Source : CompressStorage.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private Rectangle CompareImageDifference(Image src, Image dst)
{
Debug.replacedert(src != null && dst != null);
Debug.replacedert(src.Width == dst.Width && src.Height == dst.Height);
Debug.replacedert(src.PixelFormat == dst.PixelFormat);
int width = src.Width;
int height = src.Height;
Rectangle rect = new Rectangle(0, 0, width, height);
try
{
int minX = -1, maxX = -1, minY = -1, maxY = -1;
Bitmap b0 = new Bitmap(src);
BitmapData d0 = b0.LockBits(rect, ImageLockMode.ReadOnly, src.PixelFormat);
Bitmap b1 = new Bitmap(dst);
BitmapData d1 = b1.LockBits(rect, ImageLockMode.ReadOnly, dst.PixelFormat);
unsafe
{
int* p0 = (int*)d0.Scan0;
int* p1 = (int*)d1.Scan0;
int offset = 0;
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
offset = width * y + x;
if ((*(p0 + offset)) != (*(p1 + offset)))
{
minX = minX < 0 ? x : (x < minX ? x : minX);
maxX = maxX < 0 ? x : (x > maxX ? x : maxX);
minY = minY < 0 ? y : (y < minY ? y : minY);
maxY = maxY < 0 ? y : (y > maxY ? y : maxY);
}
}
}
}
b0.UnlockBits(d0);
b1.UnlockBits(d1);
minX = minX < 0 ? 0 : minX;
maxX = maxX < 0 ? 0 : maxX;
minY = minY < 0 ? 0 : minY;
maxY = maxY < 0 ? 0 : maxY;
Debug.replacedert(minX <= maxX && minY <= maxY);
rect.X = minX;
rect.Y = minY;
rect.Width = (maxX == minX) ? 1 : (maxX - minX);
rect.Height = (maxY == minY) ? 1 : (maxY - minY);
Debug.replacedert(0 <= rect.X && rect.X < width && 0 <= rect.Y && rect.Y < height);
Debug.replacedert(rect.Width > 0 && rect.Height > 0);
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
return rect;
}
19
Source : ImageCompression.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static void SaveGrayScale(Image image, string filename, uint nColors, bool fTransparent)
{
// GIF codec supports 256 colors maximum, monochrome minimum.
if (nColors > 256)
nColors = 256;
if (nColors < 2)
nColors = 2;
// Make a new 8-BPP indexed bitmap that is the same size as the source image.
int Width = image.Width;
int Height = image.Height;
// Always use PixelFormat8bppIndexed because that is the color
// table-based interface to the GIF codec.
Bitmap bitmap = new Bitmap(Width,
Height,
PixelFormat.Format8bppIndexed);
// Create a color palette big enough to hold the colors you want.
ColorPalette pal = GetColorPalette(nColors);
// Initialize a new color table with entries that are determined
// by some optimal palette-finding algorithm; for demonstration
// purposes, use a grayscale.
for (uint i = 0; i < nColors; i++)
{
uint Alpha = 0xFF; // Colors are opaque.
uint Intensity = i * 0xFF / (nColors - 1); // Even distribution.
// The GIF encoder makes the first entry in the palette
// that has a ZERO alpha the transparent color in the GIF.
// Pick the first one arbitrarily, for demonstration purposes.
if (i == 0 && fTransparent) // Make this color index...
Alpha = 0; // Transparent
// Create a gray scale for demonstration purposes.
// Otherwise, use your favorite color reduction algorithm
// and an optimum palette for that algorithm generated here.
// For example, a color histogram, or a median cut palette.
pal.Entries[i] = Color.FromArgb((int)Alpha,
(int)Intensity,
(int)Intensity,
(int)Intensity);
}
// Set the palette into the new Bitmap object.
bitmap.Palette = pal;
// Use GetPixel below to pull out the color data of Image.
// Because GetPixel isn't defined on an Image, make a copy
// in a Bitmap instead. Make a new Bitmap that is the same size as the
// image that you want to export. Or, try to
// interpret the native pixel format of the image by using a LockBits
// call. Use PixelFormat32BppARGB so you can wrap a Graphics
// around it.
Bitmap BmpCopy = new Bitmap(Width,
Height,
PixelFormat.Format32bppArgb);
{
Graphics g = Graphics.FromImage(BmpCopy);
g.PageUnit = GraphicsUnit.Pixel;
// Transfer the Image to the Bitmap
g.DrawImage(image, 0, 0, Width, Height);
// g goes out of scope and is marked for garbage collection.
// Force it, just to keep things clean.
g.Dispose();
}
// Lock a rectangular portion of the bitmap for writing.
BitmapData bitmapData;
Rectangle rect = new Rectangle(0, 0, Width, Height);
bitmapData = bitmap.LockBits(
rect,
ImageLockMode.WriteOnly,
PixelFormat.Format8bppIndexed);
// Write to the temporary buffer that is provided by LockBits.
// Copy the pixels from the source image in this loop.
// Because you want an index, convert RGB to the appropriate
// palette index here.
IntPtr pixels = bitmapData.Scan0;
unsafe
{
// Get the pointer to the image bits.
// This is the unsafe operation.
byte* pBits;
if (bitmapData.Stride > 0)
pBits = (byte*)pixels.ToPointer();
else
// If the Stide is negative, Scan0 points to the last
// scanline in the buffer. To normalize the loop, obtain
// a pointer to the front of the buffer that is located
// (Height-1) scanlines previous.
pBits = (byte*)pixels.ToPointer() + bitmapData.Stride * (Height - 1);
uint stride = (uint)Math.Abs(bitmapData.Stride);
for (uint row = 0; row < Height; ++row)
{
for (uint col = 0; col < Width; ++col)
{
// Map palette indexes for a gray scale.
// If you use some other technique to color convert,
// put your favorite color reduction algorithm here.
Color pixel; // The source pixel.
// The destination pixel.
// The pointer to the color index byte of the
// destination; this real pointer causes this
// code to be considered unsafe.
byte* p8bppPixel = pBits + row * stride + col;
pixel = BmpCopy.GetPixel((int)col, (int)row);
// Use luminance/chrominance conversion to get grayscale.
// Basically, turn the image into black and white TV.
// Do not calculate Cr or Cb because you
// discard the color anyway.
// Y = Red * 0.299 + Green * 0.587 + Blue * 0.114
// This expression is best as integer math for performance,
// however, because GetPixel listed earlier is the slowest
// part of this loop, the expression is left as
// floating point for clarity.
double luminance = (pixel.R * 0.299) +
(pixel.G * 0.587) +
(pixel.B * 0.114);
// Gray scale is an intensity map from black to white.
// Compute the index to the grayscale entry that
// approximates the luminance, and then round the index.
// Also, constrain the index choices by the number of
// colors to do, and then set that pixel's index to the
// byte value.
*p8bppPixel = (byte)(luminance * (nColors - 1) / 255 + 0.5);
} /* end loop for col */
} /* end loop for row */
} /* end unsafe */
// To commit the changes, unlock the portion of the bitmap.
bitmap.UnlockBits(bitmapData);
bitmap.Save(filename, ImageFormat.Png);
// Bitmap goes out of scope here and is also marked for
// garbage collection.
// Pal is referenced by bitmap and goes away.
// BmpCopy goes out of scope here and is marked for garbage
// collection. Force it, because it is probably quite large.
// The same applies to bitmap.
BmpCopy.Dispose();
bitmap.Dispose();
}
19
Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static Image CreateImageByData(byte[] bsData, int width, int height, ColorPalette palette)
{
Image img;
try
{
Rectangle rect = new Rectangle(0, 0, width, height);
PixelFormat format = palette == null ? PixelFormat.Format16bppRgb555 : PixelFormat.Format8bppIndexed;
Bitmap bmp = new Bitmap(width, height, format);
if (palette != null)
bmp.Palette = palette;
var bmpData = bmp.LockBits(rect, ImageLockMode.WriteOnly, format);
{
int length = Math.Abs(bmpData.Stride) * bmpData.Height;
IntPtr pData = new IntPtr(bmpData.Scan0.ToInt64() + (bmpData.Stride > 0 ? 0 : bmpData.Stride * (bmpData.Height - 1)));
Debug.replacedert(bsData.Length >= length);
Marshal.Copy(bsData, 0, pData, length);
}
bmp.UnlockBits(bmpData);
img = bmp;
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return img;
}
19
Source : _CompressEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private Rectangle CompareImage(Image src, Image dst)
{
Debug.replacedert(src != null && dst != null);
Debug.replacedert(src.Width == dst.Width && src.Height == dst.Height);
Debug.replacedert(src.PixelFormat == dst.PixelFormat);
int width = src.Width;
int height = src.Height;
Rectangle rect = new Rectangle(0, 0, width, height);
int minX = -1, maxX = -1, minY = -1, maxY = -1;
Bitmap b0 = new Bitmap(src);
BitmapData d0 = b0.LockBits(rect, ImageLockMode.ReadOnly, src.PixelFormat);
Bitmap b1 = new Bitmap(dst);
BitmapData d1 = b1.LockBits(rect, ImageLockMode.ReadOnly, dst.PixelFormat);
unsafe
{
int* p0 = (int*)d0.Scan0;
int* p1 = (int*)d1.Scan0;
int offset = 0;
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
offset = width * y + x;
if ((*(p0 + offset)) != (*(p1 + offset)))
{
minX = minX < 0 ? x : (x < minX ? x : minX);
maxX = maxX < 0 ? x : (x > maxX ? x : maxX);
minY = minY < 0 ? y : (y < minY ? y : minY);
maxY = maxY < 0 ? y : (y > maxY ? y : maxY);
}
}
}
minX = minX < 0 ? 0 : minX;
maxX = maxX < 0 ? 0 : maxX;
minY = minY < 0 ? 0 : minY;
maxY = maxY < 0 ? 0 : maxY;
Debug.replacedert(minX <= maxX && minY <= maxY);
}
b0.UnlockBits(d0);
b1.UnlockBits(d1);
rect.X = minX;
rect.Y = minY;
rect.Width = maxX - minX;
rect.Height = maxY - minY;
return rect;
}
19
Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static Bitmap IndexedColorBitmap(Image img)
{
Bitmap newImage = null;
try
{
int width = img.Width;
int height = img.Height;
Rectangle rect = new Rectangle(0, 0, width, height);
Bitmap newBitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
newBitmap.Palette = ColorIndexedPalette;
using (Bitmap srcBitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(srcBitmap))
{
g.PageUnit = GraphicsUnit.Pixel;
g.DrawImage(img, 0, 0);
}
var srcData = srcBitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
var newData = newBitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
unsafe
{
int srcStride = Math.Abs(srcData.Stride);
int newStride = Math.Abs(newData.Stride);
byte* pSrc = (byte*)srcData.Scan0.ToPointer() + (srcData.Stride > 0 ? 0 : (srcData.Stride * (height - 1)));
byte* pNew = (byte*)newData.Scan0.ToPointer() + (newData.Stride > 0 ? 0 : (newData.Stride * (height - 1)));
PixelData* ps;
byte* pn;
for (uint y = 0; y < height; y++)
{
ps = (PixelData*)(pSrc + (srcStride * y));
pn = pNew + (newStride * y);
for (uint x = 0; x < width; x++)
{
//*pn = (byte)(((ps->red >> 6) << 4) | ((ps->green >> 6) << 2) | (ps->blue >> 6));
byte r = (byte)(ps->red * 3 / 255.0);
byte g = (byte)(ps->green * 3 / 255.0);
byte b = (byte)(ps->blue * 3 / 255.0);
Debug.replacedert(r < 4 && g < 4 && b < 4);
*pn = (byte)(r << 4 | g << 2 | b);
++ps;
++pn;
}
}
}
srcBitmap.UnlockBits(srcData);
newBitmap.UnlockBits(newData);
srcData = null;
newData = null;
}
newImage = newBitmap;
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return newImage;
}
19
Source : ImageCompressEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static byte[] ExtractImageData(Bitmap bitmap)
{
byte[] bsData = null;
{
int width = bitmap.Width;
int height = bitmap.Height;
Rectangle rect = new Rectangle(0, 0, width, height);
var data = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);
try
{
IntPtr pData = new IntPtr(data.Scan0.ToInt64() + (data.Stride > 0 ? 0 : data.Stride * (height - 1)));
int length = Math.Abs(data.Stride) * data.Height;
bsData = new byte[length];
Marshal.Copy(pData, bsData, 0, length);
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
finally
{
bitmap.UnlockBits(data);
}
}
return bsData;
}
19
Source : ImageCompression.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static Image GrayScaleCompress(Image image)
{
uint nColors = 256;
bool fTransparent = true;
// Make a new 8-BPP indexed bitmap that is the same size as the source image.
int Width = image.Width;
int Height = image.Height;
// Always use PixelFormat8bppIndexed because that is the color
// table-based interface to the GIF codec.
Bitmap bitmap = new Bitmap(Width,
Height,
PixelFormat.Format8bppIndexed);
// Create a color palette big enough to hold the colors you want.
ColorPalette pal = GetColorPalette(nColors);
// Initialize a new color table with entries that are determined
// by some optimal palette-finding algorithm; for demonstration
// purposes, use a grayscale.
for (uint i = 0; i < nColors; i++)
{
uint Alpha = 0xFF; // Colors are opaque.
uint Intensity = i * 0xFF / (nColors - 1); // Even distribution.
// The GIF encoder makes the first entry in the palette
// that has a ZERO alpha the transparent color in the GIF.
// Pick the first one arbitrarily, for demonstration purposes.
if (i == 0 && fTransparent) // Make this color index...
Alpha = 0; // Transparent
// Create a gray scale for demonstration purposes.
// Otherwise, use your favorite color reduction algorithm
// and an optimum palette for that algorithm generated here.
// For example, a color histogram, or a median cut palette.
pal.Entries[i] = Color.FromArgb((int)Alpha,
(int)Intensity,
(int)Intensity,
(int)Intensity);
}
// Set the palette into the new Bitmap object.
bitmap.Palette = pal;
// Use GetPixel below to pull out the color data of Image.
// Because GetPixel isn't defined on an Image, make a copy
// in a Bitmap instead. Make a new Bitmap that is the same size as the
// image that you want to export. Or, try to
// interpret the native pixel format of the image by using a LockBits
// call. Use PixelFormat32BppARGB so you can wrap a Graphics
// around it.
Bitmap BmpCopy = new Bitmap(Width,
Height,
PixelFormat.Format32bppArgb);
{
Graphics g = Graphics.FromImage(BmpCopy);
g.PageUnit = GraphicsUnit.Pixel;
// Transfer the Image to the Bitmap
g.DrawImage(image, 0, 0, Width, Height);
// g goes out of scope and is marked for garbage collection.
// Force it, just to keep things clean.
g.Dispose();
}
// Lock a rectangular portion of the bitmap for writing.
BitmapData bitmapData;
Rectangle rect = new Rectangle(0, 0, Width, Height);
bitmapData = bitmap.LockBits(
rect,
ImageLockMode.WriteOnly,
PixelFormat.Format8bppIndexed);
// Write to the temporary buffer that is provided by LockBits.
// Copy the pixels from the source image in this loop.
// Because you want an index, convert RGB to the appropriate
// palette index here.
IntPtr pixels = bitmapData.Scan0;
unsafe
{
// Get the pointer to the image bits.
// This is the unsafe operation.
byte* pBits;
if (bitmapData.Stride > 0)
pBits = (byte*)pixels.ToPointer();
else
// If the Stide is negative, Scan0 points to the last
// scanline in the buffer. To normalize the loop, obtain
// a pointer to the front of the buffer that is located
// (Height-1) scanlines previous.
pBits = (byte*)pixels.ToPointer() + bitmapData.Stride * (Height - 1);
uint stride = (uint)Math.Abs(bitmapData.Stride);
for (uint row = 0; row < Height; ++row)
{
for (uint col = 0; col < Width; ++col)
{
// Map palette indexes for a gray scale.
// If you use some other technique to color convert,
// put your favorite color reduction algorithm here.
Color pixel; // The source pixel.
// The destination pixel.
// The pointer to the color index byte of the
// destination; this real pointer causes this
// code to be considered unsafe.
byte* p8bppPixel = pBits + row * stride + col;
pixel = BmpCopy.GetPixel((int)col, (int)row);
// Use luminance/chrominance conversion to get grayscale.
// Basically, turn the image into black and white TV.
// Do not calculate Cr or Cb because you
// discard the color anyway.
// Y = Red * 0.299 + Green * 0.587 + Blue * 0.114
// This expression is best as integer math for performance,
// however, because GetPixel listed earlier is the slowest
// part of this loop, the expression is left as
// floating point for clarity.
double luminance = (pixel.R * 0.299) +
(pixel.G * 0.587) +
(pixel.B * 0.114);
// Gray scale is an intensity map from black to white.
// Compute the index to the grayscale entry that
// approximates the luminance, and then round the index.
// Also, constrain the index choices by the number of
// colors to do, and then set that pixel's index to the
// byte value.
*p8bppPixel = (byte)(luminance * (nColors - 1) / 255 + 0.5);
} /* end loop for col */
} /* end loop for row */
} /* end unsafe */
// To commit the changes, unlock the portion of the bitmap.
bitmap.UnlockBits(bitmapData);
// Bitmap goes out of scope here and is also marked for
// garbage collection.
// Pal is referenced by bitmap and goes away.
// BmpCopy goes out of scope here and is marked for garbage
// collection. Force it, because it is probably quite large.
// The same applies to bitmap.
BmpCopy.Dispose();
//bitmap.Dispose();
return bitmap;
}
19
Source : ImageCompression.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static Image GrayScale(Image image)
{
// Make a new 8-BPP indexed bitmap that is the same size as the source image.
int Width = image.Width;
int Height = image.Height;
int nColors = 256;
Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);
// fill palette
ColorPalette pal = bitmap.Palette;
for (int i = 0; i < nColors; i++)
{
int Alpha = (i == 0) ? 0x00 : 0xFF;
int Intensity = i * 0xFF / (nColors - 1);
pal.Entries[i] = Color.FromArgb(Alpha, Intensity, Intensity, Intensity);
}
Rectangle rect = new Rectangle(0, 0, Width, Height);
BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
// Write to the temporary buffer that is provided by LockBits.
// Copy the pixels from the source image in this loop.
// Because you want an index, convert RGB to the appropriate
// palette index here.
IntPtr pixels = bitmapData.Scan0;
unsafe
{
// Get the pointer to the image bits.
// This is the unsafe operation.
byte* pBits;
if (bitmapData.Stride > 0)
pBits = (byte*)pixels.ToPointer();
else
// If the Stide is negative, Scan0 points to the last
// scanline in the buffer. To normalize the loop, obtain
// a pointer to the front of the buffer that is located
// (Height-1) scanlines previous.
pBits = (byte*)pixels.ToPointer() + bitmapData.Stride * (Height - 1);
uint stride = (uint)Math.Abs(bitmapData.Stride);
for (uint row = 0; row < Height; ++row)
{
for (uint col = 0; col < Width; ++col)
{
//Color pixel; // The source pixel.
// The destination pixel.
// The pointer to the color index byte of the
// destination; this real pointer causes this
// code to be considered unsafe.
byte* p8bppPixel = pBits + row * stride + col;
//pixel = image.GetPixel((int)col, (int)row);
// Use luminance/chrominance conversion to get grayscale.
// Basically, turn the image into black and white TV.
// Do not calculate Cr or Cb because you
// discard the color anyway.
// Y = Red * 0.299 + Green * 0.587 + Blue * 0.114
// This expression is best as integer math for performance,
// however, because GetPixel listed earlier is the slowest
// part of this loop, the expression is left as
// floating point for clarity.
//double luminance = (pixel.R * 0.299) +
// (pixel.G * 0.587) +
// (pixel.B * 0.114);
// Gray scale is an intensity map from black to white.
// Compute the index to the grayscale entry that
// approximates the luminance, and then round the index.
// Also, constrain the index choices by the number of
// colors to do, and then set that pixel's index to the
// byte value.
//*p8bppPixel = (byte)(luminance * (nColors - 1) / 255 + 0.5);
} /* end loop for col */
} /* end loop for row */
} /* end unsafe */
// To commit the changes, unlock the portion of the bitmap.
bitmap.UnlockBits(bitmapData);
// Bitmap goes out of scope here and is also marked for
// garbage collection.
// Pal is referenced by bitmap and goes away.
// BmpCopy goes out of scope here and is marked for garbage
// collection. Force it, because it is probably quite large.
// The same applies to bitmap.
bitmap.Dispose();
return null;
}
19
Source : GaussianBlur.cs
with MIT License
from AlexanderPro
with MIT License
from AlexanderPro
public Bitmap Process(int radial)
{
var newAlpha = new int[_width * _height];
var newRed = new int[_width * _height];
var newGreen = new int[_width * _height];
var newBlue = new int[_width * _height];
var dest = new int[_width * _height];
Parallel.Invoke(
() => gaussBlur_4(_alpha, newAlpha, radial),
() => gaussBlur_4(_red, newRed, radial),
() => gaussBlur_4(_green, newGreen, radial),
() => gaussBlur_4(_blue, newBlue, radial));
Parallel.For(0, dest.Length, _pOptions, i =>
{
if (newAlpha[i] > 255) newAlpha[i] = 255;
if (newRed[i] > 255) newRed[i] = 255;
if (newGreen[i] > 255) newGreen[i] = 255;
if (newBlue[i] > 255) newBlue[i] = 255;
if (newAlpha[i] < 0) newAlpha[i] = 0;
if (newRed[i] < 0) newRed[i] = 0;
if (newGreen[i] < 0) newGreen[i] = 0;
if (newBlue[i] < 0) newBlue[i] = 0;
dest[i] = (int)((uint)(newAlpha[i] << 24) | (uint)(newRed[i] << 16) | (uint)(newGreen[i] << 8) | (uint)newBlue[i]);
});
var image = new Bitmap(_width, _height);
var rct = new Rectangle(0, 0, image.Width, image.Height);
var bits2 = image.LockBits(rct, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
Marshal.Copy(dest, 0, bits2.Scan0, dest.Length);
image.UnlockBits(bits2);
return image;
}
19
Source : Form1.cs
with MIT License
from ALEXGREENALEX
with MIT License
from ALEXGREENALEX
public Bitmap Gray16To8bppIndexed(Bitmap BmpIn)
{
if (BmpIn.PixelFormat != PixelFormat.Format16bppGrayScale)
throw new BadImageFormatException();
byte[] ImageData = new byte[BmpIn.Width * BmpIn.Height * 2];
Rectangle Re = new Rectangle(0, 0, BmpIn.Width, BmpIn.Height);
BitmapData BmpData = BmpIn.LockBits(Re, ImageLockMode.ReadOnly, BmpIn.PixelFormat);
Marshal.Copy(BmpData.Scan0, ImageData, 0, ImageData.Length);
BmpIn.UnlockBits(BmpData);
byte[] ImageData2 = new byte[BmpIn.Width * BmpIn.Height];
for (long i = 0; i < ImageData2.LongLength; i++)
ImageData2[i] = ImageData[i * 2 + 1];
ImageData = null;
Bitmap BmpOut = new Bitmap(BmpIn.Width, BmpIn.Height, PixelFormat.Format8bppIndexed);
BmpData = BmpOut.LockBits(Re, ImageLockMode.WriteOnly, BmpOut.PixelFormat);
Marshal.Copy(ImageData2, 0, BmpData.Scan0, ImageData2.Length);
BmpOut.UnlockBits(BmpData);
ImageData2 = null;
BmpData = null;
ColorPalette GrayPalette = BmpOut.Palette;
Color[] GrayColors = GrayPalette.Entries;
for (int i = 0; i < GrayColors.Length; i++)
GrayColors[i] = Color.FromArgb(i, i, i);
BmpOut.Palette = GrayPalette;
return BmpOut;
}
19
Source : SensorNotifyIcon.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private Icon CreateTransparentIcon() {
string text = GetString();
int count = 0;
for (int i = 0; i < text.Length; i++)
if ((text[i] >= '0' && text[i] <= '9') || text[i] == '-')
count++;
bool small = count > 2;
graphics.Clear(Color.Black);
TextRenderer.DrawText(graphics, text, small ? smallFont : font,
new Point(-2, small ? 1 : 0), Color.White, Color.Black);
BitmapData data = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
IntPtr Scan0 = data.Scan0;
int numBytes = bitmap.Width * bitmap.Height * 4;
byte[] bytes = new byte[numBytes];
Marshal.Copy(Scan0, bytes, 0, numBytes);
bitmap.UnlockBits(data);
byte red, green, blue;
for (int i = 0; i < bytes.Length; i += 4) {
blue = bytes[i];
green = bytes[i + 1];
red = bytes[i + 2];
bytes[i] = color.B;
bytes[i + 1] = color.G;
bytes[i + 2] = color.R;
bytes[i + 3] = (byte)(0.3 * red + 0.59 * green + 0.11 * blue);
}
return IconFactory.Create(bytes, bitmap.Width, bitmap.Height,
PixelFormat.Format32bppArgb);
}
19
Source : SensorNotifyIcon.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private Icon CreatePercentageIcon() {
try {
graphics.Clear(Color.Transparent);
} catch (ArgumentException) {
graphics.Clear(Color.Black);
}
graphics.FillRectangle(darkBrush, 0.5f, -0.5f, bitmap.Width - 2, bitmap.Height);
float value = sensor.Value.GetValueOrDefault();
float y = 0.16f * (100 - value);
graphics.FillRectangle(brush, 0.5f, -0.5f + y, bitmap.Width - 2, bitmap.Height - y);
graphics.DrawRectangle(pen, 1, 0, bitmap.Width - 3, bitmap.Height - 1);
BitmapData data = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
byte[] bytes = new byte[bitmap.Width * bitmap.Height * 4];
Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
bitmap.UnlockBits(data);
return IconFactory.Create(bytes, bitmap.Width, bitmap.Height,
PixelFormat.Format32bppArgb);
}
19
Source : BitmapHelper.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public static void SetAlphaChanelValue(Bitmap image, byte value)
{
if (image == null)
throw new ArgumentNullException("image");
if (image.PixelFormat != PixelFormat.Format32bppArgb)
throw new ArgumentException("Wrong PixelFormat");
BitmapData bitmapData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
unsafe
{
PixelData* pPixel = (PixelData*)bitmapData.Scan0;
for (int i = 0; i < bitmapData.Height; i++)
{
for (int j = 0; j < bitmapData.Width; j++)
{
pPixel->A = value;
pPixel++;
}
pPixel += bitmapData.Stride - (bitmapData.Width * 4);
}
}
image.UnlockBits(bitmapData);
}
19
Source : Program.cs
with MIT License
from altimesh
with MIT License
from altimesh
static void Main(string[] args)
{
// open the input image and lock its content for read operations
Bitmap baseImage = (Bitmap)Image.FromFile("lena512.bmp");
PixelFormat format = baseImage.PixelFormat;
var lockedSource = baseImage.LockBits(new Rectangle(0, 0, baseImage.Width, baseImage.Height), ImageLockMode.ReadOnly, format);
IntPtr srcData = lockedSource.Scan0;
int imageBytes = baseImage.Width * baseImage.Height;
// create a result image with same pixel format (8 bits per pixel) and lock its content for write operations
Bitmap resImage = new Bitmap(baseImage.Width, baseImage.Height, format);
BitmapData lockedDest = resImage.LockBits(new Rectangle(0, 0, baseImage.Width, baseImage.Height), ImageLockMode.WriteOnly, format);
IntPtr destData = lockedDest.Scan0;
// pin images memory for cuda
cuda.HostRegister(srcData, imageBytes, (uint) cudaHostAllocFlags.cudaHostAllocMapped);
cuda.HostRegister(destData, imageBytes, (uint)cudaHostAllocFlags.cudaHostAllocMapped);
IntPtr d_input, d_result;
cuda.HostGetDevicePointer(out d_input, srcData, cudaGetDevicePointerFlags.cudaReserved);
cuda.HostGetDevicePointer(out d_result, destData, cudaGetDevicePointerFlags.cudaReserved);
// run the kernel
HybRunner runner = HybRunner.Cuda("Sobel_Lock_CUDA.dll").SetDistrib(32, 32, 16, 16, 1, 0);
runner.Wrap(new Program()).ComputeSobel(d_result, d_input, baseImage.Width, baseImage.Height);
cuda.DeviceSynchronize();
// unregister pinned memory
cuda.HostUnregister(destData);
cuda.HostUnregister(srcData);
// unlock images
resImage.UnlockBits(lockedDest);
baseImage.UnlockBits(lockedSource);
// and save result
resImage.Palette = baseImage.Palette;
resImage.Save("lena_sobel.bmp");
try { Process.Start("lena_sobel.bmp");} catch {} // catch exception for non interactives machines
}
19
Source : Program.cs
with MIT License
from altimesh
with MIT License
from altimesh
static void Main(string[] args)
{
// open the input image and lock its content for read operations
Bitmap baseImage = (Bitmap)Image.FromFile("lena512.bmp");
PixelFormat format = baseImage.PixelFormat;
var lockedSource = baseImage.LockBits(new Rectangle(0, 0, baseImage.Width, baseImage.Height), ImageLockMode.ReadOnly, format);
IntPtr srcData = lockedSource.Scan0;
int imageBytes = baseImage.Width * baseImage.Height;
// create a result image with same pixel format (8 bits per pixel) and lock its content for write operations
Bitmap resImage = new Bitmap(baseImage.Width, baseImage.Height, format);
BitmapData lockedDest = resImage.LockBits(new Rectangle(0, 0, baseImage.Width, baseImage.Height), ImageLockMode.WriteOnly, format);
IntPtr destData = lockedDest.Scan0;
// pin images memory for cuda
cuda.HostRegister(srcData, imageBytes, (uint) cudaHostAllocFlags.cudaHostAllocMapped);
cuda.HostRegister(destData, imageBytes, (uint)cudaHostAllocFlags.cudaHostAllocMapped);
IntPtr d_input, d_result;
cuda.HostGetDevicePointer(out d_input, srcData, cudaGetDevicePointerFlags.cudaReserved);
cuda.HostGetDevicePointer(out d_result, destData, cudaGetDevicePointerFlags.cudaReserved);
// run the kernel
HybRunner runner = HybRunner.Cuda().SetDistrib(32, 32, 16, 16, 1, 0);
runner.Wrap(new Program()).ComputeSobel(d_result, d_input, baseImage.Width, baseImage.Height);
cuda.DeviceSynchronize();
// unregister pinned memory
cuda.HostUnregister(destData);
cuda.HostUnregister(srcData);
// unlock images
resImage.UnlockBits(lockedDest);
baseImage.UnlockBits(lockedSource);
// and save result
resImage.Palette = baseImage.Palette;
resImage.Save("lena_sobel.bmp");
try { Process.Start("lena_sobel.bmp");} catch {} // catch exception for non interactives machines
}
19
Source : 02-lock-gpu.cs
with MIT License
from altimesh
with MIT License
from altimesh
static void Main(string[] args)
{
// open the input image and lock its content for read operations
Bitmap baseImage = (Bitmap)Image.FromFile("../../images/lena_highres_greyscale.bmp");
PixelFormat format = baseImage.PixelFormat;
var lockedSource = baseImage.LockBits(new Rectangle(0, 0, baseImage.Width, baseImage.Height), ImageLockMode.ReadOnly, format);
IntPtr srcData = lockedSource.Scan0;
int imageBytes = baseImage.Width * baseImage.Height;
// create a result image with same pixel format (8 bits per pixel) and lock its content for write operations
Bitmap resImage = new Bitmap(baseImage.Width, baseImage.Height, format);
BitmapData lockedDest = resImage.LockBits(new Rectangle(0, 0, baseImage.Width, baseImage.Height), ImageLockMode.WriteOnly, format);
IntPtr destData = lockedDest.Scan0;
// pin images memory for cuda
cuda.HostRegister(srcData, imageBytes, (uint) cudaHostAllocFlags.cudaHostAllocMapped);
cuda.HostRegister(destData, imageBytes, (uint)cudaHostAllocFlags.cudaHostAllocMapped);
IntPtr d_input, d_result;
cuda.HostGetDevicePointer(out d_input, srcData, cudaGetDevicePointerFlags.cudaReserved);
cuda.HostGetDevicePointer(out d_result, destData, cudaGetDevicePointerFlags.cudaReserved);
// run the kernel
HybRunner runner = HybRunner.Cuda().SetDistrib(32, 32, 16, 16, 1, 0);
runner.Wrap(new Program()).ComputeSobel(d_result, d_input, baseImage.Width, baseImage.Height);
cuda.DeviceSynchronize();
// unregister pinned memory
cuda.HostUnregister(destData);
cuda.HostUnregister(srcData);
// unlock images
resImage.UnlockBits(lockedDest);
baseImage.UnlockBits(lockedSource);
// and save result
resImage.Palette = baseImage.Palette;
resImage.Save("lena_highres_sobel.bmp");
try { Process.Start("lena_highres_sobel.bmp");} catch {} // catch exception for non interactives machines
}
19
Source : BitmapHelper.cs
with Apache License 2.0
from AnkiUniversal
with Apache License 2.0
from AnkiUniversal
private static System.Drawing.Color CalculateAverageBoundariesColor(Bitmap bm)
{
int width = bm.Width;
int height = bm.Height;
// cutting corners, will fail on anything else but 32 and 24 bit images
int bppModifier = bm.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb ? 4 : 3;
BitmapData srcData = bm.LockBits(new System.Drawing.Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.ReadOnly, bm.PixelFormat);
try
{
PixelColors avgColorNew;
PixelColors avgColorOld = GetAverageColor(width, height, srcData, bppModifier);
while (true)
{
avgColorNew = GetAverageColor(width, height, srcData, bppModifier, avgColorOld);
if (!avgColorNew.IsDiffer(avgColorOld, 5))
break;
avgColorOld = avgColorNew;
}
return System.Drawing.Color.FromArgb(avgColorNew.Red, avgColorNew.Green, avgColorNew.Blue);
}
finally
{
bm.UnlockBits(srcData);
}
}
19
Source : JocrImageConvert.cs
with Apache License 2.0
from AnkiUniversal
with Apache License 2.0
from AnkiUniversal
public static GrayImage BitmapToGrayImageJocr(Bitmap bitmap)
{
BitmapData srcData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
try
{
Jocr.GrayImage image = new Jocr.GrayImage(srcData.Width, srcData.Height);
uint size = (uint)(srcData.Width * srcData.Height);
switch (srcData.PixelFormat)
{
case PixelFormat.Format32bppArgb:
image.Pixels = Argb32ToGray(srcData, size);
break;
default:
throw new FormatException("Wrong image format!");
}
return image;
}
finally
{
bitmap.UnlockBits(srcData);
}
}
19
Source : DockersTabsControl.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
protected unsafe void RedrawTabs()
{
// Determine length and width in pixels
int tabslength = 0;
for(int i = 0; i < this.TabPages.Count; i++)
{
Rectangle r = this.GetTabRect(i);
tabslength += r.Height;
}
tabslength += 4;
int tabswidth = this.ItemSize.Height + 2;
// Dispose old image
if(tabsimage != null)
{
tabsimage.Dispose();
tabsimage = null;
}
if(VisualStyleInformation.IsSupportedByOS && VisualStyleInformation.IsEnabledByUser)
{
StringFormat drawformat = new StringFormat();
drawformat.Alignment = StringAlignment.Center;
drawformat.HotkeyPrefix = HotkeyPrefix.None;
drawformat.LineAlignment = StringAlignment.Center;
// Create images
tabsimage = new Bitmap(tabswidth, tabslength, PixelFormat.Format32bppArgb);
Bitmap drawimage = new Bitmap(tabslength, tabswidth, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(drawimage);
// Render the tabs (backwards when right-aligned)
int posoffset = 0;
int selectedposoffset = -1;
int start = (this.Alignment == TabAlignment.Left) ? 0 : (this.TabPages.Count - 1);
int end = (this.Alignment == TabAlignment.Left) ? this.TabPages.Count : -1;
int step = (this.Alignment == TabAlignment.Left) ? 1 : -1;
for(int i = start; i != end; i += step)
{
VisualStyleRenderer renderer;
Rectangle tr = this.GetTabRect(i);
// Tab selected?
if(i == this.SelectedIndex)
{
// We will draw this later
selectedposoffset = posoffset;
}
else
{
if(i == highlighttab)
renderer = new VisualStyleRenderer(VisualStyleElement.Tab.TabItem.Hot);
else
renderer = new VisualStyleRenderer(VisualStyleElement.Tab.TabItem.Normal);
// Draw tab
Rectangle r = new Rectangle(posoffset + 2, 2, tr.Height, tr.Width - 2);
renderer.DrawBackground(g, r);
g.DrawString(this.TabPages[i].Text, this.Font, SystemBrushes.ControlText, new RectangleF(r.Location, r.Size), drawformat);
}
posoffset += tr.Height;
}
// Render the selected tab, because it is slightly larger and overlapping the others
if(selectedposoffset > -1)
{
VisualStyleRenderer renderer = new VisualStyleRenderer(VisualStyleElement.Tab.TabItem.Pressed);
Rectangle tr = this.GetTabRect(this.SelectedIndex);
Rectangle r = new Rectangle(selectedposoffset, 0, tr.Height + 4, tr.Width);
renderer.DrawBackground(g, r);
g.DrawString(this.TabPages[this.SelectedIndex].Text, this.Font, SystemBrushes.ControlText, new RectangleF(r.X, r.Y, r.Width, r.Height - 2), drawformat);
}
// Rotate the image and copy to tabsimage
BitmapData drawndata = drawimage.LockBits(new Rectangle(0, 0, drawimage.Size.Width, drawimage.Size.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
BitmapData targetdata = tabsimage.LockBits(new Rectangle(0, 0, tabsimage.Size.Width, tabsimage.Size.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
int* dd = (int*)drawndata.Scan0.ToPointer();
int* td = (int*)targetdata.Scan0.ToPointer();
if(this.Alignment == TabAlignment.Right)
{
for(int y = 0; y < drawndata.Height; y++)
{
for(int x = 0; x < drawndata.Width; x++)
{
td[(drawndata.Width - 1 - x) * targetdata.Width + y] = *dd;
dd++;
}
}
}
else
{
for(int y = 0; y < drawndata.Height; y++)
{
for(int x = 0; x < drawndata.Width; x++)
{
td[x * targetdata.Width + (drawndata.Height - 1 - y)] = *dd;
dd++;
}
}
}
drawimage.UnlockBits(drawndata);
tabsimage.UnlockBits(targetdata);
// Clean up
g.Dispose();
drawimage.Dispose();
}
}
19
Source : HighResImage.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
protected override void LocalLoadImage()
{
IImageReader reader;
MemoryStream mem;
byte[] membytes;
Graphics g = null;
// Checks
if(this.IsImageLoaded) return;
if((width == 0) || (height == 0)) return;
lock(this)
{
// Create texture bitmap
try
{
if(bitmap != null) bitmap.Dispose();
bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
BitmapData bitmapdata = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
PixelColor* pixels = (PixelColor*)bitmapdata.Scan0.ToPointer();
General.ZeroMemory(new IntPtr(pixels), width * height * sizeof(PixelColor));
bitmap.UnlockBits(bitmapdata);
g = Graphics.FromImage(bitmap);
}
catch(Exception e)
{
// Unable to make bitmap
General.ErrorLogger.Add(ErrorType.Error, "Unable to load texture image '" + this.Name + "'. " + e.GetType().Name + ": " + e.Message);
loadfailed = true;
}
if(!loadfailed)
{
// Go for all patches
foreach(TexturePatch p in patches)
{
// Get the patch data stream
Stream patchdata = General.Map.Data.GetPatchData(p.lumpname);
if(patchdata != null)
{
// Copy patch data to memory
patchdata.Seek(0, SeekOrigin.Begin);
membytes = new byte[(int)patchdata.Length];
patchdata.Read(membytes, 0, (int)patchdata.Length);
mem = new MemoryStream(membytes);
mem.Seek(0, SeekOrigin.Begin);
// Get a reader for the data
reader = ImageDataFormat.GetImageReader(mem, ImageDataFormat.DOOMPICTURE, General.Map.Data.Palette);
if(reader is UnknownImageReader)
{
// Data is in an unknown format!
General.ErrorLogger.Add(ErrorType.Error, "Patch lump '" + p.lumpname + "' data format could not be read, while loading texture '" + this.Name + "'");
loadfailed = true;
}
else
{
// Get the patch
mem.Seek(0, SeekOrigin.Begin);
Bitmap patchbmp = null;
try { patchbmp = reader.ReadAsBitmap(mem); }
catch(InvalidDataException)
{
// Data cannot be read!
General.ErrorLogger.Add(ErrorType.Error, "Patch lump '" + p.lumpname + "' data format could not be read, while loading texture '" + this.Name + "'");
loadfailed = true;
}
if(patchbmp != null)
{
// Adjust patch alpha
if(p.alpha < 1.0f)
{
BitmapData bmpdata = null;
try
{
bmpdata = patchbmp.LockBits(new Rectangle(0, 0, patchbmp.Size.Width, patchbmp.Size.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
}
catch(Exception e)
{
General.ErrorLogger.Add(ErrorType.Error, "Cannot lock image '" + p.lumpname + "' for alpha adjustment. " + e.GetType().Name + ": " + e.Message);
}
if(bmpdata != null)
{
PixelColor* pixels = (PixelColor*)(bmpdata.Scan0.ToPointer());
int numpixels = bmpdata.Width * bmpdata.Height;
for(PixelColor* cp = pixels + numpixels - 1; cp >= pixels; cp--)
{
cp->a = (byte)((((float)cp->a * PixelColor.BYTE_TO_FLOAT) * p.alpha) * 255.0f);
}
patchbmp.UnlockBits(bmpdata);
}
}
// Draw the patch on the texture image
Rectangle tgtrect = new Rectangle(p.x, p.y, patchbmp.Size.Width, patchbmp.Size.Height);
g.DrawImageUnscaledAndClipped(patchbmp, tgtrect);
patchbmp.Dispose();
}
}
// Done
mem.Dispose();
}
else
{
// Missing a patch lump!
General.ErrorLogger.Add(ErrorType.Error, "Missing patch lump '" + p.lumpname + "' while loading texture '" + this.Name + "'");
loadfailed = true;
}
}
}
// Dispose bitmap if load failed
if(loadfailed && (bitmap != null))
{
bitmap.Dispose();
bitmap = null;
}
// Preplaced on to base
base.LocalLoadImage();
}
}
19
Source : DoomColormapReader.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public Bitmap ReadAsBitmap(Stream stream)
{
BitmapData bitmapdata;
PixelColorBlock pixeldata;
PixelColor* targetdata;
int width, height;
Bitmap bmp;
// Read pixel data
pixeldata = ReadAsPixelData(stream, out width, out height);
if(pixeldata != null)
{
try
{
// Create bitmap and lock pixels
bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
bitmapdata = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
targetdata = (PixelColor*)bitmapdata.Scan0.ToPointer();
// Copy the pixels
General.CopyMemory(targetdata, pixeldata.Pointer, (uint)(width * height * sizeof(PixelColor)));
// Done
bmp.UnlockBits(bitmapdata);
}
catch(Exception e)
{
// Unable to make bitmap
General.ErrorLogger.Add(ErrorType.Error, "Unable to make Doom flat data. " + e.GetType().Name + ": " + e.Message);
return null;
}
}
else
{
// Failed loading picture
bmp = null;
}
// Return result
return bmp;
}
19
Source : DoomColormapReader.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public unsafe void DrawToPixelData(Stream stream, PixelColor* target, int targetwidth, int targetheight, int x, int y)
{
Bitmap bmp;
BitmapData bmpdata;
PixelColor* pixels;
int ox, oy, tx, ty;
int width, height;
// Get bitmap
bmp = ReadAsBitmap(stream);
width = bmp.Size.Width;
height = bmp.Size.Height;
// Lock bitmap pixels
bmpdata = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
pixels = (PixelColor*)bmpdata.Scan0.ToPointer();
// Go for all pixels in the original image
for(ox = 0; ox < width; ox++)
{
for(oy = 0; oy < height; oy++)
{
// Copy this pixel?
if(pixels[oy * width + ox].a > 0.5f)
{
// Calculate target pixel and copy when within bounds
tx = x + ox;
ty = y + oy;
if((tx >= 0) && (tx < targetwidth) && (ty >= 0) && (ty < targetheight))
target[ty * targetwidth + tx] = pixels[oy * width + ox];
}
}
}
// Done
bmp.UnlockBits(bmpdata);
bmp.Dispose();
}
19
Source : DoomPictureReader.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public Bitmap ReadAsBitmap(Stream stream, out int offsetx, out int offsety)
{
BitmapData bitmapdata;
PixelColorBlock pixeldata;
PixelColor* targetdata;
int width, height;
Bitmap bmp;
// Read pixel data
pixeldata = ReadAsPixelData(stream, out width, out height, out offsetx, out offsety);
if(pixeldata != null)
{
// Create bitmap and lock pixels
try
{
bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
bitmapdata = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
targetdata = (PixelColor*)bitmapdata.Scan0.ToPointer();
// Copy the pixels
General.CopyMemory(targetdata, pixeldata.Pointer, (uint)(width * height * sizeof(PixelColor)));
// Done
bmp.UnlockBits(bitmapdata);
}
catch(Exception e)
{
// Unable to make bitmap
General.ErrorLogger.Add(ErrorType.Error, "Unable to make Doom picture data. " + e.GetType().Name + ": " + e.Message);
return null;
}
}
else
{
// Failed loading picture
bmp = null;
}
// Return result
return bmp;
}
19
Source : FileImageReader.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public void DrawToPixelData(Stream stream, PixelColor* target, int targetwidth, int targetheight, int x, int y)
{
Bitmap bmp;
BitmapData bmpdata;
PixelColor* pixels;
int ox, oy, tx, ty;
int width, height;
// Get bitmap
bmp = ReadAsBitmap(stream);
if(bmp != null)
{
width = bmp.Size.Width;
height = bmp.Size.Height;
// Lock bitmap pixels
bmpdata = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
pixels = (PixelColor*)bmpdata.Scan0.ToPointer();
// Go for all pixels in the original image
for(ox = 0; ox < width; ox++)
{
for(oy = 0; oy < height; oy++)
{
// Copy this pixel?
if(pixels[oy * width + ox].a > 0.5f)
{
// Calculate target pixel and copy when within bounds
tx = x + ox;
ty = y + oy;
if((tx >= 0) && (tx < targetwidth) && (ty >= 0) && (ty < targetheight))
target[ty * targetwidth + tx] = pixels[oy * width + ox];
}
}
}
// Done
bmp.UnlockBits(bmpdata);
bmp.Dispose();
}
else
{
throw new InvalidDataException();
}
}
19
Source : ImageData.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
protected virtual void LocalLoadImage()
{
BitmapData bmpdata = null;
lock(this)
{
// Bitmap loaded successfully?
if(bitmap != null)
{
// Bitmap has incorrect format?
if(bitmap.PixelFormat != PixelFormat.Format32bppArgb)
{
if(dynamictexture)
throw new Exception("Dynamic images must be in 32 bits ARGB format.");
//General.ErrorLogger.Add(ErrorType.Warning, "Image '" + name + "' does not have A8R8G8B8 pixel format. Conversion was needed.");
Bitmap oldbitmap = bitmap;
try
{
// Convert to desired pixel format
bitmap = new Bitmap(oldbitmap.Size.Width, oldbitmap.Size.Height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
g.PageUnit = GraphicsUnit.Pixel;
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.SmoothingMode = SmoothingMode.None;
g.PixelOffsetMode = PixelOffsetMode.None;
g.Clear(Color.Transparent);
g.DrawImage(oldbitmap, 0, 0, oldbitmap.Size.Width, oldbitmap.Size.Height);
g.Dispose();
oldbitmap.Dispose();
}
catch(Exception e)
{
bitmap = oldbitmap;
General.ErrorLogger.Add(ErrorType.Warning, "Cannot lock image '" + name + "' for pixel format conversion. The image may not be displayed correctly.\n" + e.GetType().Name + ": " + e.Message);
}
}
// This applies brightness correction on the image
if(usecolorcorrection)
{
try
{
// Try locking the bitmap
bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Size.Width, bitmap.Size.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
}
catch(Exception e)
{
General.ErrorLogger.Add(ErrorType.Warning, "Cannot lock image '" + name + "' for color correction. The image may not be displayed correctly.\n" + e.GetType().Name + ": " + e.Message);
}
// Bitmap locked?
if(bmpdata != null)
{
// Apply color correction
PixelColor* pixels = (PixelColor*)(bmpdata.Scan0.ToPointer());
General.Colors.ApplColorCorrection(pixels, bmpdata.Width * bmpdata.Height);
bitmap.UnlockBits(bmpdata);
}
}
}
else
{
// Loading failed
// We still mark the image as ready so that it will
// not try loading again until Reload Resources is used
loadfailed = true;
bitmap = new Bitmap(Properties.Resources.Failed);
}
if(bitmap != null)
{
width = bitmap.Size.Width;
height = bitmap.Size.Height;
if(dynamictexture)
{
if((width != General.NextPowerOf2(width)) || (height != General.NextPowerOf2(height)))
throw new Exception("Dynamic images must have a size in powers of 2.");
}
// Do we still have to set a scale?
if((scale.x == 0.0f) && (scale.y == 0.0f))
{
if((General.Map != null) && (General.Map.Config != null))
{
scale.x = General.Map.Config.DefaultTextureScale;
scale.y = General.Map.Config.DefaultTextureScale;
}
else
{
scale.x = 1.0f;
scale.y = 1.0f;
}
}
}
// Image is ready
imagestate = ImageLoadState.Ready;
}
}
19
Source : ImageData.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public void UpdateTexture()
{
if(!dynamictexture)
throw new Exception("The image must be a dynamic image to support direct updating.");
lock(this)
{
if((texture != null) && !texture.Disposed)
{
// Lock the bitmap and texture
BitmapData bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Size.Width, bitmap.Size.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
DataRectangle texdata = texture.LockRectangle(0, LockFlags.Discard);
// Copy data
int* bp = (int*)bmpdata.Scan0.ToPointer();
int* tp = (int*)texdata.Data.DataPointer.ToPointer();
for(int y = 0; y < bmpdata.Height; y++)
{
for(int x = 0; x < bmpdata.Width; x++)
{
*tp = *bp;
bp++;
tp++;
}
// Skip extra data in texture
int extrapitch = (texdata.Pitch >> 2) - bmpdata.Width;
tp += extrapitch;
}
// Unlock
texture.UnlockRectangle(0);
bitmap.UnlockBits(bmpdata);
}
}
}
19
Source : FileImageReader.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public Bitmap ReadAsBitmap(Stream stream)
{
try
{
// Create an image in DevIL
uint imageid = 0;
ilGenImages(1, new IntPtr(&imageid));
ilBindImage(imageid);
// Read image data from stream
byte[] bytes = new byte[stream.Length - stream.Position];
stream.Read(bytes, 0, bytes.Length);
fixed(byte* bptr = bytes)
{
if(!ilLoadL(IL_TYPE_UNKNOWN, new IntPtr(bptr), (uint)bytes.Length))
throw new BadImageFormatException();
}
// Get the image properties
int width = ilGetInteger(IL_IMAGE_WIDTH);
int height = ilGetInteger(IL_IMAGE_HEIGHT);
if((width < 1) || (height < 1))
throw new BadImageFormatException();
// Convert the image to ARGB if needed
ilConvertImage(IL_BGRA, IL_UNSIGNED_BYTE);
// Copy the image pixels to a Bitmap
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
BitmapData bmpdata = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
ilCopyPixels(0, 0, 0, (uint)width, (uint)height, 1, IL_BGRA, IL_UNSIGNED_BYTE, bmpdata.Scan0);
bmp.UnlockBits(bmpdata);
// Clean up
ilDeleteImages(1, new IntPtr(&imageid));
return bmp;
}
catch(Exception e)
{
// Unable to make bitmap
General.ErrorLogger.Add(ErrorType.Error, "Unable to make file image. " + e.GetType().Name + ": " + e.Message);
return null;
}
}
19
Source : BuilderPlug.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private static Bitmap MakeTintedImage(Bitmap source, PixelColor tint)
{
BitmapData sourcedata = source.LockBits(new Rectangle(0, 0, source.Width, source.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
byte[] pixelBuffer = new byte[sourcedata.Stride * sourcedata.Height];
Marshal.Copy(sourcedata.Scan0, pixelBuffer, 0, pixelBuffer.Length);
source.UnlockBits(sourcedata);
//Translate tint color to 0.0-1.0 range
float redtint = tint.r / 256.0f;
float greentint = tint.g / 256.0f;
float bluetint = tint.b / 256.0f;
for(int k = 0; k + 4 < pixelBuffer.Length; k += 4)
{
float blue = 60 + pixelBuffer[k] * bluetint;
float green = 60 + pixelBuffer[k + 1] * greentint;
float red = 60 + pixelBuffer[k + 2] * redtint;
pixelBuffer[k] = (byte)Math.Min(255, blue);
pixelBuffer[k + 1] = (byte)Math.Min(255, green);
pixelBuffer[k + 2] = (byte)Math.Min(255, red);
}
Bitmap result = new Bitmap(source.Width, source.Height);
BitmapData resultdata = result.LockBits(new Rectangle(0, 0, result.Width, result.Height),
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
Marshal.Copy(pixelBuffer, 0, resultdata.Scan0, pixelBuffer.Length);
result.UnlockBits(resultdata);
return result;
}
See More Examples