Here are the examples of the csharp api System.Drawing.Image.Dispose() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
994 Examples
19
View Source File : WebPFile.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 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
View Source File : MainFormHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
public Icon GetNotifyIcon(Config config, Icon def)
{
try
{
Color color = ColorTranslator.FromHtml("#3399CC");
int index = (int)config.sysProxyType;
if (index > 0)
{
color = (new Color[] { Color.Red, Color.Purple, Color.DarkGreen, Color.Orange, Color.DarkSlateBlue, Color.RoyalBlue })[index - 1];
//color = ColorTranslator.FromHtml(new string[] { "#CC0066", "#CC6600", "#99CC99", "#666699" }[index - 1]);
}
int width = 128;
int height = 128;
Bitmap bitmap = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(bitmap);
SolidBrush drawBrush = new SolidBrush(color);
graphics.FillEllipse(drawBrush, new Rectangle(0, 0, width, height));
int zoom = 16;
graphics.DrawImage(new Bitmap(Properties.Resources.notify, width - zoom, width - zoom), zoom / 2, zoom / 2);
Icon createdIcon = Icon.FromHandle(bitmap.GetHicon());
drawBrush.Dispose();
graphics.Dispose();
bitmap.Dispose();
return createdIcon;
}
catch (Exception ex)
{
Utils.SaveLog(ex.Message, ex);
return def;
}
}
19
View Source File : LayoutDescriptionEx.cs
License : GNU General Public License v3.0
Project Creator : aglab2
License : GNU General Public License v3.0
Project Creator : aglab2
public void Compress()
{
var goldCompressedImage = new Bitmap(20, 20);
var darkCompressedImage = new Bitmap(20, 20);
var destRect = new Rectangle(0, 0, 20, 20);
using (var graphics = Graphics.FromImage(goldCompressedImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(goldStar, destRect, 0, 0, goldStar.Width, goldStar.Height, GraphicsUnit.Pixel, wrapMode);
}
}
goldStar.Dispose();
goldStar = goldCompressedImage;
using (var graphics = Graphics.FromImage(darkCompressedImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(darkStar, destRect, 0, 0, darkStar.Width, darkStar.Height, GraphicsUnit.Pixel, wrapMode);
}
}
darkStar.Dispose();
darkStar = darkCompressedImage;
}
19
View Source File : GraphicsManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2
License : GNU General Public License v3.0
Project Creator : aglab2
public void TestFont()
{
Image randomImage = new Bitmap(300, 50);
Graphics g = Graphics.FromImage(randomImage);
// Setup draw font: 20 symbols in max 170 width
float l = 0, r = 40, m = -1;
String measureString = new string('W', 2);
// 10 iterations is enough
for (int iter = 0; iter < 10; iter++)
{
m = (l + r) / 2;
Font drawFont = new Font(FontFamily, m);
// Measure string.
SizeF stringSize = new SizeF();
stringSize = g.MeasureString(measureString, drawFont);
float width = stringSize.Width; //should take 170
if (width < SWidth)
l = m;
else
r = m;
}
drawFontSize = m;
Console.WriteLine("Draw: {0}", m);
// Setup med font: 1 symbols in max 20 height
l = 0; r = 40; m = -1;
measureString = "W";
// 10 iterations is enough
for (int iter = 0; iter < 10; iter++)
{
m = (l + r) / 2;
Font drawFont = new Font(FontFamily, m);
// Measure string.
SizeF stringSize = new SizeF();
stringSize = g.MeasureString(measureString, drawFont);
float height = stringSize.Height; //should take HalfWidth
if (height < SWidth)
l = m;
else
r = m;
}
medFontSize = m;
Console.WriteLine("Med: {0}", m);
// Setup med font: 1 symbols in max 20 height
l = 0; r = 40; m = -1;
measureString = new string('W', 27);
// 10 iterations is enough
for (int iter = 0; iter < 10; iter++)
{
m = (l + r) / 2;
Font drawFont = new Font(FontFamily, m);
// Measure string.
SizeF stringSize = new SizeF();
stringSize = g.MeasureString(measureString, drawFont);
float width = stringSize.Width; //should take 170
float localScaleCoef = ld == null ? 1 : scaleCoef;
if (width < HalfWidth * 2 * localScaleCoef)
l = m;
else
r = m;
}
bigFontSize = m;
Console.WriteLine("Big: {0}", m);
g.Dispose();
randomImage.Dispose();
}
19
View Source File : TextureEncoder.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : 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
View Source File : Texture.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
public void Encode(Image image)
{
for(int i=0; i<Levels; i++)
{
TextureEncoder.Encode(this, image, i);
}
if (_thumbnailCache != null)
{
_thumbnailCache.Dispose();
_thumbnailCache = null;
}
}
19
View Source File : ModelGenerator.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
internal static ModelNode GenerateModel(Drawable drawable, TextureFile[] textures)
{
var random = new Random();
var materials = new Material[drawable.Materials.Count];
for (int i = 0; i < materials.Length; i++)
{
Brush brush =
new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, (byte)random.Next(0, 255),
(byte)random.Next(0, 255),
(byte)random.Next(0, 255)));
var drawableMat = drawable.Materials[i];
var texture = drawableMat.Parameters[(int)ParamNameHash.Texture] as MaterialParamTexture;
if (texture != null)
{
// 1. Try looking in the embedded texture file (if any)
var textureObj = FindTexture(drawable.AttachedTexture, texture.TextureName);
// 2. Try looking in any attached external texture dictionaries
if (textureObj == null)
{
foreach (var file in textures)
{
textureObj = FindTexture(file, texture.TextureName);
if (textureObj != null)
{
break;
}
}
}
// Generate a brush if we were successful
if (textureObj != null)
{
var bitmap = textureObj.Decode() as Bitmap;
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
bitmap.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
// For memory leak work around
bitmapSource.Freeze();
brush = new ImageBrush(bitmapSource);
(brush as ImageBrush).ViewportUnits = BrushMappingMode.Absolute;
(brush as ImageBrush).TileMode = TileMode.Tile;
bitmap.Dispose();
}
}
materials[i] = new DiffuseMaterial(brush);
}
var drawableModelGroup = new Model3DGroup();
var drawableModelNode = new ModelNode {DataModel = drawable, Model3D = drawableModelGroup, Name = "Drawable", NoCount = true};
foreach (var model in drawable.Models)
{
var modelGroup = new Model3DGroup();
var modelNode = new ModelNode {DataModel = model, Model3D = modelGroup, Name = "Model"};
drawableModelNode.Children.Add(modelNode);
foreach (var geometry in model.Geometries)
{
var geometryIndex = 0;
var geometryGroup = new Model3DGroup();
var geometryNode = new ModelNode { DataModel = geometry, Model3D = geometryGroup, Name = "Geometry" };
modelNode.Children.Add(geometryNode);
foreach (var mesh in geometry.Meshes)
{
var mesh3D = new MeshGeometry3D();
var meshNode = new ModelNode { DataModel = mesh, Model3D = null, Name = "Mesh" };
geometryNode.Children.Add(meshNode);
Data.Vertex[] vertices = mesh.DecodeVertexData();
foreach (var vertex in vertices)
{
mesh3D.Positions.Add(new Point3D(vertex.Position.X, vertex.Position.Y, vertex.Position.Z));
if (mesh.VertexHasNormal)
{
mesh3D.Normals.Add(new Vector3D(vertex.Normal.X, vertex.Normal.Y, vertex.Normal.Z));
}
if (mesh.VertexHasTexture)
{
mesh3D.TextureCoordinates.Add(new Point(vertex.TextureCoordinates[0].X, vertex.TextureCoordinates[0].Y));
}
}
ushort[] indices = mesh.DecodeIndexData();
for (int i = 0; i < mesh.FaceCount; i++)
{
mesh3D.TriangleIndices.Add(indices[i * 3 + 0]);
mesh3D.TriangleIndices.Add(indices[i * 3 + 1]);
mesh3D.TriangleIndices.Add(indices[i * 3 + 2]);
}
var material = materials[geometry.Meshes[geometryIndex].MaterialIndex];
var model3D = new GeometryModel3D(mesh3D, material);
geometryGroup.Children.Add(model3D);
meshNode.Model3D = model3D;
geometryIndex++;
}
modelGroup.Children.Add(geometryGroup);
}
drawableModelGroup.Children.Add(modelGroup);
}
return drawableModelNode;
}
19
View Source File : Texture.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
public void Dispose()
{
Info = null;
if (_thumbnailCache != null)
{
_thumbnailCache.Dispose();
_thumbnailCache = null;
}
}
19
View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ahuchjm
License : MIT License
Project Creator : 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
View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ahuchjm
License : MIT License
Project Creator : 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
View Source File : Image.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public void Dispose()
{
M_Image.Dispose();
}
19
View Source File : ImageCompression.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : 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
View Source File : ImageCompression.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private static ColorPalette GetColorPalette(uint nColors)
{
// replacedume monochrome image.
PixelFormat bitscolordepth = PixelFormat.Format1bppIndexed;
ColorPalette palette; // The Palette we are stealing
Bitmap bitmap; // The source of the stolen palette
// Determine number of colors.
if (nColors > 2)
bitscolordepth = PixelFormat.Format4bppIndexed;
if (nColors > 16)
bitscolordepth = PixelFormat.Format8bppIndexed;
// Make a new Bitmap object to get its Palette.
bitmap = new Bitmap(1, 1, bitscolordepth);
palette = bitmap.Palette; // Grab the palette
bitmap.Dispose(); // cleanup the source Bitmap
return palette; // Send the palette back
}
19
View Source File : ImageColorsConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private ColorPalette CreateNewColorPalette()
{
PixelFormat format = PixelFormat.Format1bppIndexed;
ColorPalette palette = null;
Bitmap bitmap = null;
try
{
if (this._imgColors > 2)
{
format = PixelFormat.Format4bppIndexed;
}
if (this._imgColors > 0x10)
{
format = PixelFormat.Format8bppIndexed;
}
bitmap = new Bitmap(1, 1, format);
palette = bitmap.Palette;
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
finally
{
bitmap.Dispose();
}
return palette;
}
19
View Source File : ImageColorsConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : 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
View Source File : RawInputApp_Imp.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private byte[] GetImageData(Image srcImage, out bool isGrayScale)
{
Image newImage;
if (Global.Config.AgentGrayScale)
{
newImage = new ImageColorsConverter().SaveImageWithNewColorTable(srcImage);
srcImage.Dispose();
isGrayScale = true;
}
else
{
Bitmap bmp = new Bitmap(srcImage.Width, srcImage.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
using (Graphics g = Graphics.FromImage(bmp))
{
g.DrawImage(srcImage, 0, 0);
srcImage.Dispose();
}
newImage = bmp;
isGrayScale = false;
}
byte[] bsImageData;
using (MemoryStream ms = new MemoryStream())
{
newImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
bsImageData = ms.ToArray();
newImage.Dispose();
}
return bsImageData;
}
19
View Source File : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static byte[] GrayScaleImage(byte[] bsImage, ImageFormat format)
{
Image newImage;
using (MemoryStream msImage = new MemoryStream(bsImage))
{
var srcImage = Image.FromStream(msImage);
newImage = GrayScaleImage(srcImage);
//newImage = new ImageColorsConverter().SaveImageWithNewColorTable(srcImage);
srcImage.Dispose();
}
byte[] bsData;
using (MemoryStream msData = new MemoryStream())
{
newImage.Save(msData, format);
bsData = msData.ToArray();
newImage.Dispose();
}
return bsData;
}
19
View Source File : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static byte[] ShortColorImage(byte[] bsImage, ImageFormat format)
{
Image newImage;
using (MemoryStream msImage = new MemoryStream(bsImage))
{
var srcImage = Image.FromStream(msImage);
newImage = ShortColorImage(srcImage);
srcImage.Dispose();
}
byte[] bsData;
using (MemoryStream msData = new MemoryStream())
{
newImage.Save(msData, format);
bsData = msData.ToArray();
newImage.Dispose();
}
return bsData;
}
19
View Source File : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : 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
View Source File : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : 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
View Source File : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : 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
View Source File : ImageCompressor.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public bool CompressImageData(bfbd.UltraRecord.Core.Snapshot sshot)
{
bool transparent = false;
Image srcImage = Deserialize(sshot.ImageData);
if (Global.Config.GrayScale)
{
var grayImage = ImageCompressEngine.GrayScaleImage(srcImage);
srcImage.Dispose();
sshot.ImageData = Serialize(grayImage);
sshot.IsGrayScale = true;
grayImage.Dispose();
UpdateBackground(null, null);
}
else
{
var colorImage = ImageCompressEngine.ShortColorImage(srcImage);
srcImage.Dispose();
if (_bkgImage == null)
UpdateBackground(sshot, colorImage);
else if (_bkgSnapshot.WindowHandle != sshot.WindowHandle)
UpdateBackground(sshot, colorImage);
else if (colorImage.Width != _bkgImage.Width || colorImage.Height != _bkgImage.Height)
UpdateBackground(sshot, colorImage);
else
{
var transparentImage = ImageCompressEngine.TransparentColorImage(_bkgImage, colorImage, 0.1f);
if (transparentImage == null)
UpdateBackground(sshot, colorImage);
else
{
colorImage.Dispose();
colorImage = transparentImage;
transparent = true;
}
}
sshot.IsGrayScale = false;
sshot.ImageData = Serialize(colorImage);
if (transparent)
sshot.BackgroundId = _bkgSnapshot.SnapshotId;
}
return transparent;
}
19
View Source File : ImageCompressor.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private void UpdateBackground(Snapshot sshot, Image img)
{
if (_bkgImage != null)
_bkgImage.Dispose();
_bkgSnapshot = sshot;
_bkgImage = img;
}
19
View Source File : ImageCompressor.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public void CompressSnapshot(bfbd.UltraRecord.Core.Snapshot sshot, bool isGrayScale)
{
Debug.replacedert(sshot.ImageData != null && sshot.ImageData.Length > 0);
using (MemoryStream ms = new MemoryStream(sshot.ImageData))
{
var img = Image.FromStream(ms);
var bmp = isGrayScale ? ImageCompressEngine.GrayScaleBitmap(img) : ImageCompressEngine.ColorValueBitmap(img);
img.Dispose();
bool isBackground;
byte[] bsData = CompressImageData(sshot.SnapshotId, bmp, out isBackground);
Debug.replacedert(sshot.ScreenWidth == bmp.Width && sshot.ScreenHeight == bmp.Height);
sshot.ScreenWidth = bmp.Width;
sshot.ScreenHeight = bmp.Height;
sshot.IsGrayScale = isGrayScale;
sshot.ImageData = bsData;
if (!isBackground)
sshot.BackgroundId = _background.SnapshotId;
bmp.Dispose();
}
}
19
View Source File : ImageCompression.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : 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
View Source File : ImageCompression.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : 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
View Source File : ImageCompression.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : 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
View Source File : ImagePacker.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
public int PackImage(
IEnumerable<string> imageFiles,
bool requirePowerOfTwo,
bool requireSquareImage,
int maximumWidth,
int maximumHeight,
int imagePadding,
bool generateMap,
out Bitmap outputImage,
out Dictionary<string, Rectangle> outputMap)
{
files = new List<string>(imageFiles);
requirePow2 = requirePowerOfTwo;
requireSquare = requireSquareImage;
outputWidth = maximumWidth;
outputHeight = maximumHeight;
padding = imagePadding;
outputImage = null;
outputMap = null;
// make sure our dictionaries are cleared before starting
imageSizes.Clear();
imagePlacement.Clear();
// get the sizes of all the images
foreach (var filePath in files)
{
Bitmap bitmap;
using (var b = new Bitmap(filePath))
{
bitmap = new Bitmap(b); //FIXED! DARN NOOBS LOCKING MY FILESS!!!!! :trollface: - Alan, May 21, 3199BC
b.Dispose();
}
imageSizes.Add(filePath, bitmap.Size);
}
// sort our files by file size so we place large sprites first
files.Sort(
(f1, f2) =>
{
Size b1 = imageSizes[f1];
Size b2 = imageSizes[f2];
int c = -b1.Width.CompareTo(b2.Width);
if (c != 0)
return c;
c = -b1.Height.CompareTo(b2.Height);
if (c != 0)
return c;
return f1.CompareTo(f2);
});
// try to pack the images
if (!PackImageRectangles())
return -2;
// make our output image
outputImage = CreateOutputImage();
if (outputImage == null)
return -3;
if (generateMap)
{
// go through our image placements and replace the width/height found in there with
// each image's actual width/height (since the ones in imagePlacement will have padding)
string[] keys = new string[imagePlacement.Keys.Count];
imagePlacement.Keys.CopyTo(keys, 0);
foreach (var k in keys)
{
// get the actual size
Size s = imageSizes[k];
// get the placement rectangle
Rectangle r = imagePlacement[k];
// set the proper size
r.Width = s.Width;
r.Height = s.Height;
// insert back into the dictionary
imagePlacement[k] = r;
}
// copy the placement dictionary to the output
outputMap = new Dictionary<string, Rectangle>();
foreach (var pair in imagePlacement)
{
outputMap.Add(pair.Key, pair.Value);
}
}
// clear our dictionaries just to free up some memory
imageSizes.Clear();
imagePlacement.Clear();
return 0;
}
19
View Source File : ImagePacker.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
private Bitmap CreateOutputImage()
{
Bitmap outputImage = new Bitmap(outputWidth, outputHeight, PixelFormat.Format32bppArgb);
// draw all the images into the output image
foreach (var image in files)
{
Rectangle location = imagePlacement[image];
//BUGFIX
//WUUUUUUUUUUUUUUTTTTTTTTTTTT??? what kinda code is this that reads replaced twice? :(
//TODO: fix all this sucky replaced!
Bitmap bitmap;
using (var b = new Bitmap(image))
{
bitmap = new Bitmap(b); //FIXED! DARN NOOBS LOCKING MY FILESS!!!!! :trollface: - Alan, May 21, 3199BC
b.Dispose();
}
//END WUUUUUUUUTTTTTTT
// copy pixels over to avoid antialiasing or any other side effects of drawing
// the subimages to the output image using Graphics
for (int x = 0; x < bitmap.Width; x++)
for (int y = 0; y < bitmap.Height; y++)
outputImage.SetPixel(location.X + x, location.Y + y, bitmap.GetPixel(x, y));
}
return outputImage;
}
19
View Source File : SensorGadget.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public override void Dispose() {
largeFont.Dispose();
largeFont = null;
smallFont.Dispose();
smallFont = null;
darkWhite.Dispose();
darkWhite = null;
stringFormat.Dispose();
stringFormat = null;
trimStringFormat.Dispose();
trimStringFormat = null;
alignRightStringFormat.Dispose();
alignRightStringFormat = null;
back.Dispose();
back = null;
barFore.Dispose();
barFore = null;
barBack.Dispose();
barBack = null;
background.Dispose();
background = null;
if (image != null) {
image.Dispose();
image = null;
}
if (fore != null) {
fore.Dispose();
fore = null;
}
base.Dispose();
}
19
View Source File : SensorGadget.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
private void DrawBackground(Graphics g) {
int w = Size.Width;
int h = Size.Height;
if (w != background.Width || h != background.Height) {
background.Dispose();
background = new Bitmap(w, h, PixelFormat.Format32bppPArgb);
using (Graphics graphics = Graphics.FromImage(background)) {
DrawImageWidthBorder(graphics, w, h, back, topBorder, bottomBorder,
leftBorder, rightBorder);
if (fore != null)
DrawImageWidthBorder(graphics, w, h, fore, topBorder, bottomBorder,
leftBorder, rightBorder);
if (image != null) {
int width = w - leftBorder - rightBorder;
int height = h - topBorder - bottomBorder;
float xRatio = width / (float)image.Width;
float yRatio = height / (float)image.Height;
float destWidth, destHeight;
float xOffset, yOffset;
if (xRatio < yRatio) {
destWidth = width;
destHeight = image.Height * xRatio;
xOffset = 0;
yOffset = 0.5f * (height - destHeight);
} else {
destWidth = image.Width * yRatio;
destHeight = height;
xOffset = 0.5f * (width - destWidth);
yOffset = 0;
}
graphics.DrawImage(image,
new RectangleF(leftBorder + xOffset, topBorder + yOffset,
destWidth, destHeight));
}
}
}
g.DrawImageUnscaled(background, 0, 0);
}
19
View Source File : SensorNotifyIcon.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public void Dispose() {
Icon icon = notifyIcon.Icon;
notifyIcon.Icon = null;
if (icon != null)
icon.Dispose();
notifyIcon.Dispose();
if (brush != null)
brush.Dispose();
if (darkBrush != null)
darkBrush.Dispose();
pen.Dispose();
graphics.Dispose();
bitmap.Dispose();
font.Dispose();
smallFont.Dispose();
}
19
View Source File : ImageCreator.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
private static void SaveAsImage(IPrintable doreplacedent, string path,
ImageFormat format, bool selectedOnly, bool transparent)
{
const int Margin = 20;
RectangleF areaF = doreplacedent.GetPrintingArea(selectedOnly);
areaF.Offset(0.5F, 0.5F);
Rectangle area = Rectangle.FromLTRB((int) areaF.Left, (int) areaF.Top,
(int) Math.Ceiling(areaF.Right), (int) Math.Ceiling(areaF.Bottom));
if (format == ImageFormat.Emf) // Save to metafile
{
Graphics metaG = control.CreateGraphics();
IntPtr hc = metaG.GetHdc();
Graphics g = null;
try
{
// Set drawing parameters
Metafile meta = new Metafile(path, hc);
g = Graphics.FromImage(meta);
g.SmoothingMode = SmoothingMode.HighQuality;
if (DiagramEditor.Settings.Default.UseClearTypeForImages)
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
else
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.TranslateTransform(-area.Left, -area.Top);
// Draw image
IGraphics graphics = new GdiGraphics(g);
doreplacedent.Print(graphics, selectedOnly, Style.CurrentStyle);
meta.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(
string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
Strings.ErrorsReason, ex.Message),
Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
metaG.ReleaseHdc();
metaG.Dispose();
if (g != null)
g.Dispose();
}
}
else // Save to rastered image
{
int width = area.Width + Margin * 2;
int height = area.Height + Margin * 2;
PixelFormat pixelFormat;
if (transparent)
pixelFormat = PixelFormat.Format32bppArgb;
else
pixelFormat = PixelFormat.Format24bppRgb;
using (Bitmap image = new Bitmap(width, height, pixelFormat))
using (Graphics g = Graphics.FromImage(image))
{
// Set drawing parameters
g.SmoothingMode = SmoothingMode.HighQuality;
if (DiagramEditor.Settings.Default.UseClearTypeForImages && !transparent)
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
else
g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
g.TranslateTransform(Margin - area.Left, Margin - area.Top);
// Draw image
if (!transparent)
g.Clear(Style.CurrentStyle.BackgroundColor);
IGraphics graphics = new GdiGraphics(g);
doreplacedent.Print(graphics, selectedOnly, Style.CurrentStyle);
try
{
image.Save(path, format);
}
catch (Exception ex)
{
MessageBox.Show(
string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
Strings.ErrorsReason, ex.Message),
Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
19
View Source File : EmbeddedResources.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public static Image GetImage(string name) {
name = "OpenHardwareMonitor.Resources." + name;
string[] names =
replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();
for (int i = 0; i < names.Length; i++) {
if (names[i].Replace('\\', '.') == name) {
using (Stream stream = replacedembly.GetExecutingreplacedembly().
GetManifestResourceStream(names[i])) {
// "You must keep the stream open for the lifetime of the Image."
Image image = Image.FromStream(stream);
// so we just create a copy of the image
Bitmap bitmap = new Bitmap(image);
// and dispose it right here
image.Dispose();
return bitmap;
}
}
}
return new Bitmap(1, 1);
}
19
View Source File : HttpServer.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
private void ServeResourceImage(HttpListenerResponse response, string name) {
name = "OpenHardwareMonitor.Resources." + name;
string[] names =
replacedembly.GetExecutingreplacedembly().GetManifestResourceNames();
for (int i = 0; i < names.Length; i++) {
if (names[i].Replace('\\', '.') == name) {
using (Stream stream = replacedembly.GetExecutingreplacedembly().
GetManifestResourceStream(names[i])) {
Image image = Image.FromStream(stream);
response.ContentType = "image/png";
try {
Stream output = response.OutputStream;
using (MemoryStream ms = new MemoryStream()) {
image.Save(ms, ImageFormat.Png);
ms.WriteTo(output);
}
output.Close();
} catch (HttpListenerException) {
}
image.Dispose();
response.Close();
return;
}
}
}
response.StatusCode = 404;
response.Close();
}
19
View Source File : GraphicsRenderContext.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public override void CleanUp()
{
var imagesToRelease = imageCache.Keys.Where(i => !imagesInUse.Contains(i));
foreach (var i in imagesToRelease)
{
var image = this.GetImage(i);
image.Dispose();
imageCache.Remove(i);
}
imagesInUse.Clear();
}
19
View Source File : MainForm.cs
License : Apache License 2.0
Project Creator : alibaba
License : Apache License 2.0
Project Creator : alibaba
private void mainPictureBox_Move(object sender, MouseEventArgs e)
{
if (e.X < rgIMD[cur].w + 2 * extend && e.Y < rgIMD[cur].h + 2 * extend)
{
this.Cursor = Cursors.Cross;
Click0Label.Text = "" + e.X + "/" + (rgIMD[cur].w + 2 * extend) + ", " + e.Y + "/" + (rgIMD[cur].w + 2 * extend);
if (ptr == -1)
{
Bitmap dest = (Bitmap)bmp.Clone();
Graphics g = Graphics.FromImage(dest);
Pen p = new Pen(Color.Blue, 1);
g.DrawLine(p, new Point(e.X, e.Y - 20), new Point(e.X, e.Y + 20));
g.DrawLine(p, new Point(e.X - 20, e.Y), new Point(e.X + 20, e.Y));
g.Dispose();
p.Dispose();
Graphics g1 = this.mainPictureBox.CreateGraphics();
g1.DrawImage(dest, new Point(0, 0));
g1.Dispose();
dest.Dispose();
}
else if (ptr == 0) {
Bitmap dest = (Bitmap)bmp.Clone();
Graphics g = Graphics.FromImage(dest);
Pen p = new Pen(Color.Blue, 1);
newpoint[0] = clkpoint[0];
newpoint[2].X = e.X;
newpoint[2].Y = e.Y;
newpoint[1].X = clkpoint[0].X;
newpoint[1].Y = e.Y;
newpoint[3].X = e.X;
newpoint[3].Y = clkpoint[0].Y;
g.DrawPolygon(p, newpoint);
g.Dispose();
p.Dispose();
Graphics g1 = this.mainPictureBox.CreateGraphics();
g1.DrawImage(dest, new Point(0, 0));
g1.Dispose();
dest.Dispose();
}
else if (ptr == 1)
{
Bitmap dest = (Bitmap)bmp.Clone();
Graphics g = Graphics.FromImage(dest);
Pen p = new Pen(Color.Blue, 1);
if (clkpoint[1].X < clkpoint[0].X)
{
newpoint[0] = new Point(clkpoint[1].X, clkpoint[1].Y);
newpoint[2] = new Point(clkpoint[0].X, clkpoint[0].Y);
}
else
{
newpoint[0] = new Point(clkpoint[0].X, clkpoint[0].Y);
newpoint[2] = new Point(clkpoint[1].X, clkpoint[1].Y);
}
double pang = Math.Atan2((double)(e.Y - newpoint[0].Y), (double)(e.X - newpoint[0].X));
ang = (int)(pang / Math.PI * 180.0);
Click2Label.Text = "" + ang + "°";
if (ang == 0 || ang == 90 || ang == -90)
{
newpoint[1] = new Point(newpoint[0].X, newpoint[2].Y);
newpoint[3] = new Point(newpoint[2].X, newpoint[0].Y);
}
else
{
double alp = ang / 180.0 * Math.PI;
double beta = Math.Atan2((double)(newpoint[2].Y - newpoint[0].Y), (double)(newpoint[2].X - newpoint[0].X));
double le = Math.Sqrt((newpoint[2].Y - newpoint[0].Y) * (newpoint[2].Y - newpoint[0].Y) + (newpoint[2].X - newpoint[0].X) * (newpoint[2].X - newpoint[0].X));
int mx = (int)(le * Math.Cos(alp - beta) * Math.Cos(alp));
int my = (int)(le * Math.Cos(alp - beta) * Math.Sin(alp));
newpoint[1] = new Point(newpoint[0].X + mx, newpoint[0].Y + my);
newpoint[3] = new Point(newpoint[2].X - mx, newpoint[2].Y - my);
}
g.DrawPolygon(p,newpoint);
g.Dispose();
p.Dispose();
Graphics g1 = this.mainPictureBox.CreateGraphics();
g1.DrawImage(dest, new Point(0, 0));
g1.Dispose();
dest.Dispose();
}
}
else
{
this.Cursor = Cursors.Default;
Click0Label.Text = "" + e.X + "/" + (rgIMD[cur].w + 2 * extend) + ", " + e.Y + "/" + (rgIMD[cur].w + 2 * extend);
}
}
19
View Source File : MainForm.cs
License : Apache License 2.0
Project Creator : alibaba
License : Apache License 2.0
Project Creator : alibaba
private void sealButton_Click(object sender, EventArgs e)
{
if (1 == ptr && clkpoint[0].X != clkpoint[1].X && clkpoint[0].Y != clkpoint[1].Y)
{
newpoint[0] = clkpoint[0];
newpoint[2] = clkpoint[1];
newpoint[1].X = clkpoint[0].X;
newpoint[1].Y = clkpoint[1].Y;
newpoint[3].X = clkpoint[1].X;
newpoint[3].Y = clkpoint[0].Y;
ang = 0;
Bitmap dest = (Bitmap)bmp.Clone();
Graphics g = Graphics.FromImage(dest);
Pen p = new Pen(Color.Blue, 1);
g.DrawPolygon(p, newpoint);
g.Dispose();
p.Dispose();
Graphics g1 = this.mainPictureBox.CreateGraphics();
g1.DrawImage(dest, new Point(0, 0));
g1.Dispose();
dest.Dispose();
ptr = 2;
sealButton.Enabled = false;
Confirm.Enabled = true;
Click2Label.Text = "" + ang + "°";
}
else
{
MessageBox.Show("Wrong Seal!");
}
//OperateClick();
}
19
View Source File : ImageMetaData.cs
License : Apache License 2.0
Project Creator : alibaba
License : Apache License 2.0
Project Creator : alibaba
public Image GetImg()
{
Image tmp_img = null;
if (null == img)
{
try
{
img = Image.FromFile(path);
ratio = 1.0f;
height = img.Height;
width = img.Width;
//MessageBox.Show(MainForm.maxH.ToString() + "," + MainForm.maxW.ToString());
if (1.0 * height / (MainForm.maxH-2*extend) > 1.0 * width / (MainForm.maxW-2*extend))
{
if (height > (MainForm.maxH-2*extend))
{
ratio = 1.0f * (MainForm.maxH-2*extend) / height;
}
}
else
{
if (width > (MainForm.maxW-2*extend))
{
ratio = 1.0f * (MainForm.maxW-2*extend) / width;
}
}
//tmp_img = (Bitmap)img.Clone();
if (ratio < 1.0f)
{
//MessageBox.Show("ERROR");
Image souImg = img;
h = Convert.ToInt32(ratio * height);
w = Convert.ToInt32(ratio * width);
tmp_img = new Bitmap(w+2*extend, h+2*extend);
//MessageBox.Show((h+extend).ToString() + "," + (w+extend).ToString());
Graphics g = Graphics.FromImage(tmp_img);
g.Clear(Color.White);
g.InterpolationMode = InterpolationMode.High;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(souImg, new Rectangle(extend, extend, w, h), new Rectangle(0, 0, width, height), GraphicsUnit.Pixel);
}
else
{
Image souImg = img;
h = height;
w = width;
//MessageBox.Show(h.ToString()+","+w.ToString());
tmp_img = new Bitmap(w + 2 * extend, h + 2 * extend);
Graphics g = Graphics.FromImage(tmp_img);
g.Clear(Color.White);
g.DrawImage(souImg, new Rectangle(extend, extend, w, h), new Rectangle(0, 0, width, height), GraphicsUnit.Pixel);
}
}
catch
{
img = null;
}
}
img.Dispose();
img = null;
return tmp_img;
}
19
View Source File : ImageMetaData.cs
License : Apache License 2.0
Project Creator : alibaba
License : Apache License 2.0
Project Creator : alibaba
public void deldetimg()
{
img.Dispose();
img = null;
File.Delete(path);
File.Delete(metaPath);
path = null;
metaPath = null;
}
19
View Source File : MainForm.cs
License : Apache License 2.0
Project Creator : alibaba
License : Apache License 2.0
Project Creator : alibaba
private void mainPictureBox_Click(object sender, MouseEventArgs e)
{
if (e.X < rgIMD[cur].w+2*extend && e.Y < rgIMD[cur].h+2*extend)
{
ptr++;
if (ptr < 2)
clkpoint[ptr] = new Point(e.X, e.Y);
sealButton.Enabled = false;
if (0 == ptr)
{
undoButton.Enabled = false;
clearButton.Enabled = false;
redrawButton.Enabled = true;
}
else if (1 == ptr)
{
sealButton.Enabled = true;
}
else if (2 == ptr)
{
Bitmap dest = (Bitmap)bmp.Clone();
Graphics g = Graphics.FromImage(dest);
Pen p = new Pen(Color.Blue, 1);
if (clkpoint[1].X < clkpoint[0].X)
{
newpoint[0] = new Point(clkpoint[1].X, clkpoint[1].Y);
newpoint[2] = new Point(clkpoint[0].X, clkpoint[0].Y);
}
else
{
newpoint[0] = new Point(clkpoint[0].X, clkpoint[0].Y);
newpoint[2] = new Point(clkpoint[1].X, clkpoint[1].Y);
}
double pang = Math.Atan2((double)(e.Y - newpoint[0].Y), (double)(e.X - newpoint[0].X));
ang = (int)(pang / Math.PI * 180.0);
Click2Label.Text = "" + ang + "°";
if (ang == 0 || ang == 90 || ang == -90)
{
newpoint[1] = new Point(newpoint[0].X, newpoint[2].Y);
newpoint[3] = new Point(newpoint[2].X, newpoint[0].Y);
}
else
{
double alp = ang / 180.0 * Math.PI;
double beta = Math.Atan2((double)(newpoint[2].Y - newpoint[0].Y), (double)(newpoint[2].X - newpoint[0].X));
double le = Math.Sqrt((newpoint[2].Y - newpoint[0].Y) * (newpoint[2].Y - newpoint[0].Y) + (newpoint[2].X - newpoint[0].X) * (newpoint[2].X - newpoint[0].X));
int mx = (int)(le * Math.Cos(alp - beta) * Math.Cos(alp));
int my = (int)(le * Math.Cos(alp - beta) * Math.Sin(alp));
newpoint[1] = new Point(newpoint[0].X + mx, newpoint[0].Y + my);
newpoint[3] = new Point(newpoint[2].X - mx, newpoint[2].Y - my);
}
g.DrawPolygon(p, newpoint);
g.Dispose();
p.Dispose();
Graphics g1 = this.mainPictureBox.CreateGraphics();
g1.DrawImage(dest, new Point(0, 0));
g1.Dispose();
dest.Dispose();
sealButton.Enabled = false;
Confirm.Enabled = true;
}
}
}
19
View Source File : ImageSubstitution.cs
License : MIT License
Project Creator : alkampfergit
License : MIT License
Project Creator : alkampfergit
public void Dispose()
{
Image?.Dispose();
}
19
View Source File : DrawHelper.cs
License : MIT License
Project Creator : AlturosDestinations
License : MIT License
Project Creator : AlturosDestinations
public static Image DrawBoxes(AnnotationImage image)
{
try
{
var originalBitmap = new Bitmap(image.ImagePath);
var newImageSize = new Size(originalBitmap.Width, originalBitmap.Height);
if (originalBitmap.Width > ImageSize.Width)
{
newImageSize.Height = (int)(originalBitmap.Height * (ImageSize.Width / (double)originalBitmap.Width));
newImageSize.Width = ImageSize.Width;
}
if (originalBitmap.Height > ImageSize.Height)
{
newImageSize.Width = (int)(originalBitmap.Width * (ImageSize.Height / (double)originalBitmap.Height));
newImageSize.Height = ImageSize.Height;
}
var resizedBitmap = new Bitmap(originalBitmap, newImageSize);
foreach (var id in originalBitmap.PropertyIdList)
{
resizedBitmap.SetPropertyItem(originalBitmap.GetPropertyItem(id));
}
originalBitmap.Dispose();
return resizedBitmap;
}
catch (Exception exception)
{
var bitmap = new Bitmap(ImageSize.Width, ImageSize.Height);
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.Clear(Color.White);
graphics.DrawString(exception.Message, new Font("Arial", 12), Brushes.Black, 50, 50);
}
return bitmap;
}
}
19
View Source File : DiffOverview.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
private void RenderImage()
{
if (m_Image != null)
{
m_Image.Dispose();
m_Image = null;
}
int iWidth = ClientSize.Width;
int iHeight = ClientSize.Height;
if (iWidth > 0 && iHeight > 0 && m_View != null && m_View.Lines != null)
{
//Draw a bitmap in memory that we can render from
m_Image = new Bitmap(iWidth, iHeight);
Graphics G = Graphics.FromImage(m_Image);
SolidBrush B = new SolidBrush(BackColor);
G.FillRectangle(B, 0, 0, iWidth, iHeight);
const float c_fGutter = 2.0F;
//Make sure each line is at least 1 pixel high
float fLineHeight = (float)Math.Max(1.0, GetPixelLineHeightF(1));
DiffViewLines Lines = m_View.Lines;
int iNumLines = Lines.Count;
for (int i = 0; i < iNumLines; i++)
{
DiffViewLine L = Lines[i];
if (L.Edited)
{
B.Color = DiffOptions.GetColorForEditType(L.EditType);
float fY = GetPixelLineHeightF(i);
G.FillRectangle(B, c_fGutter, fY, iWidth - 2 * c_fGutter, fLineHeight);
}
}
B.Dispose();
G.Dispose();
}
}
19
View Source File : SmartTreeView.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
private void SetStateList()
{
if (_stateImageList == null)
return;
if (_realStateImageList != null)
{
_realStateImageList.Dispose();
_realStateImageList = null;
}
_realStateImageList = new ImageList();
_realStateImageList.ImageSize = _stateImageList.ImageSize;
if (_stateImageList.Images.Count > 0)
{
Image[] list = new Image[_stateImageList.Images.Count+1];
int n = 0;
list[n++] = _stateImageList.Images[0];
foreach(Image i in _stateImageList.Images)
list[n++] = i;
_realStateImageList.Images.AddRange(list);
NativeMethods.SendMessage(Handle, 0x1109, (IntPtr)2, _realStateImageList.Handle);
n = 0;
foreach(Image i in list)
{
if(n++ > 0)
i.Dispose(); // Release temporary bitmaps
}
}
}
19
View Source File : SnippingTool.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
public static void Snip()
{
if (IsCapturing)
return;
if (Bitmap != null)
{
Bitmap.Dispose();
GC.Collect();
}
IsCapturing = true;
var screens = ScreenHelper.GetMonitorsInfo();
forms = new SnippingTool[screens.Count];
for (int i = 0; i < screens.Count; i++)
{
int horResolution = screens[i].HorizontalResolution;
int verResolution = screens[i].VerticalResolution;
int top = screens[i].MonitorArea.Top;
int left = screens[i].MonitorArea.Left;
var bitmap = new Bitmap(horResolution, verResolution, PixelFormat.Format32bppPArgb);
using (var g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(left, top, 0, 0, bitmap.Size);
}
forms[i] = new SnippingTool(bitmap, left, top, horResolution, verResolution);
forms[i].Show();
}
}
19
View Source File : SnippingTool.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
public static void CancelSnipping()
{
if (Bitmap != null)
{
Bitmap.Dispose();
GC.Collect();
}
Bitmap = null;
CloseForms();
OnCancel(new EventArgs());
}
19
View Source File : DockersTabsControl.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
protected override void Dispose(bool disposing)
{
if(tabsimage != null)
{
tabsimage.Dispose();
tabsimage = null;
}
base.Dispose(disposing);
}
19
View Source File : DockersTabsControl.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : 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
View Source File : ImageSelectorControl.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
private void ShowPreview(Image image)
{
// Dispose old image
preview.BackgroundImage = null;
if(bmp != null)
{
bmp.Dispose();
bmp = null;
}
if(image != null)
{
// Show it centered
General.DisplayZoomedImage(preview, image);
preview.Refresh();
}
}
See More Examples