Here are the examples of the csharp api System.Drawing.Graphics.FromImage(System.Drawing.Image) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1819 Examples
19
View Source File : HelpEngine.cs
License : MIT License
Project Creator : 0xLaileb
License : MIT License
Project Creator : 0xLaileb
public static Graphics GetGraphics(ref Bitmap bitmap, SmoothingMode SmoothingMode, TextRenderingHint TextRenderingHint)
{
Graphics graphics = Graphics.FromImage(bitmap);
graphics.SmoothingMode = SmoothingMode;
graphics.TextRenderingHint = TextRenderingHint;
return graphics;
}
19
View Source File : Grabber.cs
License : MIT License
Project Creator : 1CM69
License : MIT License
Project Creator : 1CM69
private void captureArea(Point TopLeft, Point BottomRight)
{
if (!(TopLeft != BottomRight))
return;
this.activated = true;
Screen.GetBounds(Screen.GetBounds(Point.Empty));
Size size = new Size(1 + BottomRight.X - TopLeft.X, 1 + BottomRight.Y - TopLeft.Y);
if (this.picture.Size != size)
this.picture = new Bitmap(size.Width, size.Height);
using (Graphics graphics = Graphics.FromImage((Image) this.picture))
graphics.CopyFromScreen(TopLeft, new Point(0, 0), this.picture.Size);
}
19
View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
public static string ScanScreen()
{
try
{
foreach (Screen screen in Screen.AllScreens)
{
using (Bitmap fullImage = new Bitmap(screen.Bounds.Width,
screen.Bounds.Height))
{
using (Graphics g = Graphics.FromImage(fullImage))
{
g.CopyFromScreen(screen.Bounds.X,
screen.Bounds.Y,
0, 0,
fullImage.Size,
CopyPixelOperation.SourceCopy);
}
int maxTry = 10;
for (int i = 0; i < maxTry; i++)
{
int marginLeft = (int)((double)fullImage.Width * i / 2.5 / maxTry);
int marginTop = (int)((double)fullImage.Height * i / 2.5 / maxTry);
Rectangle cropRect = new Rectangle(marginLeft, marginTop, fullImage.Width - marginLeft * 2, fullImage.Height - marginTop * 2);
Bitmap target = new Bitmap(screen.Bounds.Width, screen.Bounds.Height);
double imageScale = (double)screen.Bounds.Width / (double)cropRect.Width;
using (Graphics g = Graphics.FromImage(target))
{
g.DrawImage(fullImage, new Rectangle(0, 0, target.Width, target.Height),
cropRect,
GraphicsUnit.Pixel);
}
BitmapLuminanceSource source = new BitmapLuminanceSource(target);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
Result result = reader.decode(bitmap);
if (result != null)
{
string ret = result.Text;
return ret;
}
}
}
}
}
catch (Exception ex)
{
SaveLog(ex.Message, ex);
}
return string.Empty;
}
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 : Main.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
private void DrawGrids()
{
using (var g = System.Drawing.Graphics.FromImage(DisplayBox.Image))
{
g.DrawLine(Pens.Gray, (float)pivotX, (float)pivotY, DisplayBox.Width, (float)pivotY);
g.DrawLine(Pens.Gray, (float)pivotX, 0, (float)pivotX, DisplayBox.Height);
DisplayBox.Refresh();
}
}
19
View Source File : DrawGraphics.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
public static _3Matrix DrawBitmap(MouseEventArgs e, PictureBox graphicsDisplayBox, IList<Point<_3Vector, _3Vector>> pointsList, double pivotX, double pivotY)
{
decimal scaleX = 4 / (decimal)graphicsDisplayBox.Width;
decimal rotationCounterX = scaleX * e.X;
decimal scaleY = 4 / (decimal)graphicsDisplayBox.Height;
decimal rotationCounterY = scaleY * e.Y;
graphicsDisplayBox.Image = new Bitmap(graphicsDisplayBox.Width, graphicsDisplayBox.Height);
var rotationResult = RotationMatrices.RotateByAngles((float)rotationCounterY, 0, (float)rotationCounterX);
foreach (var pointPair in pointsList)
{
using (var g = System.Drawing.Graphics.FromImage(graphicsDisplayBox.Image))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
_3Vector pointA, pointB;
Pen pen;
EffectColourScheme(rotationResult, pointPair, out pointA, out pointB, out pen);
g.DrawLine(pen, (float)((pointA.a) + pointA.b + pivotX)
, (float)((pointA.c) + pivotY)
, (float)((pointB.a) + pointB.b + pivotX)
, (float)((pointB.c) + pivotY));
}
}
return rotationResult;
}
19
View Source File : DrawGraphics.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
public static void AngleAxis(_3Matrix rotationResult, PictureBox AnglePictureBox,
_3Vector AngleX,
_3Vector AngleY,
_3Vector AngleZ)
{
AnglePictureBox.Image = new Bitmap(AnglePictureBox.Width, AnglePictureBox.Height);
using (var g = System.Drawing.Graphics.FromImage(AnglePictureBox.Image))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
var resX = rotationResult.MultiplyByVector(AngleX);
var resY = rotationResult.MultiplyByVector(AngleY);
var resZ = rotationResult.MultiplyByVector(AngleZ);
for (int i = 1; i <= 19; i++)
{
g.DrawLine(Pens.Gray, i * 10, 0, i * 10, 200);//x
g.DrawLine(Pens.Gray, 0, i * 10, 200, i * 10);//y
}
var penX = new Pen(Color.LightGreen, 2);
var penY = new Pen(Color.Blue, 2);
var penZ = new Pen(Color.Red, 2);
g.DrawLine(penX, 100, 100, (float)resX.a + 100, (float)resX.c + 100);
g.DrawLine(penY, 100, 100, (float)resY.a + 100, (float)resY.c + 100);
g.DrawLine(penZ, 100, 100, (float)resZ.a + 100, (float)resZ.c + 100);
}
}
19
View Source File : ImageHack.cs
License : MIT License
Project Creator : Aeroblast
License : MIT License
Project Creator : Aeroblast
public static byte[] Warmer(byte[] data)
{
if (!prepared) PrepareWarmer();
using (Bitmap b = new Bitmap(new MemoryStream(data)))
using (Bitmap r = new Bitmap(b.Width, b.Height, PixelFormat.Format32bppArgb))
using (Graphics g = Graphics.FromImage(r))
{
g.Clear(Color.Transparent);
g.DrawImage(b, new Rectangle(0, 0, b.Width, b.Height), 0, 0, b.Width, b.Height, GraphicsUnit.Pixel, imageAttributes);
var output = new MemoryStream();
r.Save(output, ImageFormat.Bmp);
return output.ToArray();
}
}
19
View Source File : ScreenCapture.cs
License : MIT License
Project Creator : afxw
License : MIT License
Project Creator : afxw
public static Image Take()
{
var screenBounds = Screen.PrimaryScreen.Bounds;
var bitmap = new Bitmap(screenBounds.Width, screenBounds.Height);
using (var g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(
screenBounds.X, screenBounds.Y, 0, 0, bitmap.Size, CopyPixelOperation.SourceCopy
);
}
return bitmap;
}
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 : MainWindow.cs
License : GNU General Public License v3.0
Project Creator : aglab2
License : GNU General Public License v3.0
Project Creator : aglab2
private void DrawIntro()
{
menuStrip.Enabled = false;
//Steps to achieve success here!
baseImage = new Bitmap(starPicture.Width, starPicture.Height);
Graphics baseGraphics = Graphics.FromImage(baseImage);
baseGraphics.Clear(Color.Black);
baseGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
gm.graphics = Graphics.FromImage(baseImage);
gm.DrawIntro(isEmulatorStarted, isHackLoaded, isOffsetsFound);
baseGraphics.Dispose();
starPicture.Image = baseImage;
}
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 SetBackground(Image image, float opacity)
{
float Height = Width * 2;
float ratioX = Width / image.Width;
float ratioY = Height / image.Height;
float ratio = Math.Max(ratioX, ratioY);
int newWidth = (int)(image.Width * ratio);
int newHeight = (int)(image.Height * ratio);
Background = new Bitmap((int)Width, (int)Height);
using (var graphics = Graphics.FromImage(Background))
{
ColorMatrix matrix = new ColorMatrix
{
Matrix33 = opacity
};
ImageAttributes attrs = new ImageAttributes();
attrs.SetColorMatrix(matrix);
PointF p1 = new PointF(0, 0);
PointF p2 = new PointF(Width, 0);
PointF p3 = new PointF(0, Height);
float x1 = Width / ratio; float x2 = Height / ratio;
graphics.DrawImage(image, new PointF[]{ p1, p2, p3 },
new RectangleF((image.Width - x1) / 2, (image.Height - x2) / 2, x1, x2),
GraphicsUnit.Pixel, attrs);
}
}
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 : MainWindow.cs
License : GNU General Public License v3.0
Project Creator : aglab2
License : GNU General Public License v3.0
Project Creator : aglab2
private void UpdateStars(object sender)
{
isEmulatorStarted = false;
isHackLoaded = false;
isOffsetsFound = false;
try
{
if (um.IsCompleted())
{
if (!isUpdateRequested && !um.IsUpdated())
{
isUpdateRequested = true;
this.SafeInvoke((MethodInvoker)delegate
{
DialogResult result = MessageBox.Show(String.Format("Update for Star Display available!\n\n{0}\nDo you want to download it now? Press cancel to skip update", um.UpdateName()), "Update",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk);
if (result == DialogResult.Yes)
{
Process.Start(um.DownloadPath());
}
if (result == DialogResult.Cancel)
{
um.WritebackUpdate();
}
});
}
}
}
catch (Exception) { }
try
{
//if (slf != null && slf.sm != null && slf.sm.isServer)
// goto bla;
if (mm.ProcessActive())
{
this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); ResetForm(); });
return;
}
isEmulatorStarted = true;
// Well, that's just a minor magic but it works
if (mm.Getreplacedle().Contains("-"))
isHackLoaded = true;
if (!mm.isMagicDone())
{
if (magicThread == null || !magicThread.IsAlive)
{
magicThread = new Thread(doMagicThread);
magicThread.Start();
}
this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); });
return;
}
isOffsetsFound = true;
try
{
// Just do nothing
if (!mm.isReadyToRead())
return;
mm.PerformRead();
}
catch (Exception)
{
this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); ResetForm(); });
return;
}
bool mmIsInvalidated = mm == null ? false : mm.CheckInvalidated();
bool gmIsInvalidated = gm == null ? false : gm.CheckInvalidated();
bool dmIsInvalidated = dm == null ? false : dm.CheckInvalidated();
bool smIsInvalidated = false;
if (slf != null && slf.sm != null)
smIsInvalidated = slf.sm.CheckInvalidated();
bool nmIsInvalidated = false;
if (slf != null && slf.nm != null)
nmIsInvalidated = slf.nm.CheckInvalidated();
if (smIsInvalidated && slf.sm.dropFile)
{
slf.sm.dropFile = false;
mm.Stars = new byte[MemoryManager.FileLength];
mm.WriteToFile(ld.starsShown);
mm.isStarsInvalidated = true;
}
if (mmIsInvalidated && mm.isStarsInvalidated)
{
mm.isStarsInvalidated = false;
if (slf != null && slf.sm != null)
{
slf.sm.SendData(mm.Stars);
}
Console.WriteLine("MM Invalidated!");
}
if (gmIsInvalidated)
Console.WriteLine("GM Invalidated!");
if (dmIsInvalidated)
Console.WriteLine("DM Invalidated!");
if (smIsInvalidated)
{
Console.WriteLine("SM Invalidated!");
{
byte[] stars = slf.sm.AcquiredData;
bool shouldSendHelp = false;
for (int i = 0; i < stars.Count(); i++)
{
byte diff = (byte)(mm.Stars[i] ^ stars[i]);
if ((mm.Stars[i] & diff) != 0)
shouldSendHelp = true;
otherStars[i] |= (byte)(diff & stars[i]);
mm.Stars[i] = (byte)(mm.Stars[i] | stars[i]);
}
if (shouldSendHelp)
{
slf.sm.SendData(mm.Stars);
}
mm.WriteToFile(ld.starsShown);
}
if (!mm.IsDecomp)
{
var location = mm.GetLocation();
var netData = slf.sm.getNetData();
foreach (var item in netData)
{
var player = item.Key;
#if DEBUG == false
if (player != slf.GetPlayerName())
#endif
{
var data = item.Value;
if (slf is object && slf.nm is object)
{
var id = slf.nm.RegisterPlayer(player);
if (data.location == location)
mm.WriteNetState(id, data.state);
else
mm.WriteNetState(id, null);
}
}
}
}
}
if (nmIsInvalidated)
{
if (!mm.IsDecomp)
{
mm.WriteNetPatch();
var state = mm.GetMarioState();
if (slf.sm is object)
{
slf.sm.SendNet64Data(slf.GetNet64Name(), state, mm.GetLocation());
}
if (slf.nm.mustReload)
{
for (int i = 0; i < 16; i++)
{
mm.WriteNetState(i, null);
}
slf.nm.mustReload = false;
}
this.SafeInvoke((MethodInvoker)delegate { slf.UpdatePlayers(slf.nm.GetPlayers()); });
}
}
// We do not draw anything!
if (!mmIsInvalidated && !gmIsInvalidated && !smIsInvalidated && !dmIsInvalidated)
{
return;
}
gm.TestFont();
if (enableAutoDeleteToolStripMenuItem.Checked)
{
try
{
mm.DeleteStars();
}
catch (IOException)
{
MessageBox.Show("Can not modify savefiles. Trying launching with elevated rights!", "Write Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
enableAutoDeleteToolStripMenuItem.Checked = false;
}
}
//Display stars routine
baseImage = new Bitmap(starPicture.Width, starPicture.Width * 4);
Graphics baseGraphics = Graphics.FromImage(baseImage);
baseGraphics.Clear(Color.Black);
baseGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
gm.graphics = Graphics.FromImage(baseImage);
if (!sm.GetConfig(MainWindowsSettingsAction.collectablesOnlyConfigureName, false))
{
TextHighlightAction act = mm.GetCurrentLineAction(ld);
if (act != null)
{
gm.AddLineHighlight(act);
}
}
UInt16 currentCRC = mm.GetRomCRC();
if (currentCRC != oldCRC || rm == null || dmIsInvalidated)
{
oldCRC = currentCRC;
try
{
rm = new ROMManager(mm.GetROM());
try
{
if (dm != null)
{
dm.GetData();
}
string exePath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
LoadLayoutNoInvalidate(exePath + "\\layout\\" + rm.GetROMName() + ".jsml", false);
}
catch (IOException)
{
try
{
dm = new DownloadManager(rm.GetROMName() + ".jsml");
}
catch(Exception) { }
LoadDefaultLayoutNoInvalidate();
}
gm.IsFirstCall = true;
}
catch (IndexOutOfRangeException) //can be generated by box reader
{ }
catch (Exception)
{ oldCRC = 0; }
InvalidateCache();
}
int lineOffset = 0;
var actions = sm.GetConfig(MainWindowsSettingsAction.collectablesOnlyConfigureName, false) ?
mm.GetCollectablesOnlyDrawActions(ld, rm) :
mm.GetDrawActions(ld, rm, enableLockoutToolStripMenuItem.Checked ? otherStars : null);
if (actions == null) return;
foreach (var entry in actions)
{
lineOffset += entry.Execute(gm, lineOffset, sm);
}
baseGraphics.Dispose();
this.SafeInvoke(delegate {
menuStrip.Enabled = true;
starPicture.Image = baseImage;
starPicture.Height = (int) (lineOffset * gm.SHeight) + 10;
this.Height = (int)(lineOffset * gm.SHeight) + 48;
});
}
catch (Win32Exception)
{
this.SafeInvoke((MethodInvoker)delegate { ResetForm(); DrawIntro(); });
}
catch (NullReferenceException)
{
this.SafeInvoke((MethodInvoker)delegate { ResetForm(); DrawIntro(); });
}
catch (ObjectDisposedException)
{
}
finally
{
int period = (isEmulatorStarted && isHackLoaded && isOffsetsFound) ? updatePeriod : scanPeriod;
timer.Change(period, Timeout.Infinite);
}
}
19
View Source File : ImageTools.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
public static Image AdjustARGB(Image image, Color argb)
{
float a = argb.A / 255f;
float r = argb.R / 255f;
float g = argb.G / 255f;
float b = argb.B / 255f;
// Declare new ColorMatrix with ARGB values and store it in an ImageAttributes
ColorMatrix matrix = new ColorMatrix(new float[][]
{
new float[] { r, 0, 0, 0, 0 },
new float[] { 0, g, 0, 0, 0 },
new float[] { 0, 0, b, 0, 0 },
new float[] { 0, 0, 0, a, 0 },
new float[] { 0, 0, 0, 0, 1 },
});
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(matrix);
Point[] points =
{
new Point(0, 0),
new Point(image.Width, 0),
new Point(0, image.Height),
};
Rectangle rectangle = new Rectangle(0, 0, image.Width, image.Height);
Bitmap bitmap = new Bitmap(image.Width, image.Height);
Graphics graphic = Graphics.FromImage(bitmap);
// Redraw the image with new ImageAttributes
graphic.DrawImage(image, points, rectangle, GraphicsUnit.Pixel, attributes);
return bitmap;
}
19
View Source File : ImageTools.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
public static Image AddDropShadow(Image image, float shadowWidth, int shadowOpacity)
{
// Generate the basic image for the shadow shape
Image dropShadow = new Bitmap(image, image.Width, image.Height);
// Pad the image out enough to fit the additional size required by the shadow extending the original
dropShadow = PadImage(dropShadow, shadowWidth);
Graphics totalShadowGraphic = Graphics.FromImage(dropShadow);
// Draw the shadow with offset from all 4 directions
totalShadowGraphic.DrawImage(dropShadow, 0, -shadowWidth); // Up
totalShadowGraphic.DrawImage(dropShadow, 0, shadowWidth); // Down
totalShadowGraphic.DrawImage(dropShadow, -shadowWidth, 0); // Left
totalShadowGraphic.DrawImage(dropShadow, shadowWidth, 0); // Right
// Color the shadow black and apply alpha evenly
dropShadow = AdjustARGB(dropShadow, Color.FromArgb(shadowOpacity, Color.Black));
Graphics dropShadowGraphic = Graphics.FromImage(dropShadow);
// Draw the original image over the drop shadow
dropShadowGraphic.DrawImage(image, shadowWidth, shadowWidth);
return dropShadow;
}
19
View Source File : ImageTools.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
static Image PadImage(Image image, float pad)
{
// Create blank canvas
Bitmap paddedImage = new Bitmap((int)(image.Width + (pad * 2)), (int)(image.Height + (pad * 2)));
Graphics canvas = Graphics.FromImage(paddedImage);
// Draw original image centered over expanded canvas
canvas.DrawImage(image, pad, pad, image.Width, image.Height);
return paddedImage;
}
19
View Source File : ImageTools.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
public static Image RotateImage(Image image, int angle)
{
// Pythagoras on the X and Y coord of the bitmap gives us the maximum possible boundary required when all rotations considered
int newDimension = (int)Math.Ceiling(Math.Sqrt((image.Width * image.Width) + (image.Height * image.Height)));
Image newImage = new Bitmap(newDimension, newDimension);
Graphics graphic = Graphics.FromImage(newImage);
// Move the image to the center, rotate it, then move it back
graphic.TranslateTransform(newImage.Width / 2, newImage.Height / 2);
graphic.RotateTransform(angle);
graphic.TranslateTransform(-newImage.Width / 2, -newImage.Height / 2);
graphic.DrawImage(image, (newDimension - image.Width) / 2, (newDimension - image.Height) / 2, image.Width, image.Height);
return newImage;
}
19
View Source File : Map.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
public static void DrawBaseLayer()
{
// Start with the chosen base map
if (SettingsMap.IsCellModeActive())
{
backgroundLayer = new Bitmap(mapDimension, mapDimension);
if (SettingsCell.drawOutline)
{
Graphics backgroundGraphics = Graphics.FromImage(backgroundLayer);
DrawCellBackground(backgroundGraphics);
}
}
else
{
backgroundLayer = SettingsMap.layerMilitary ?
IOManager.GetImageMapMilitary() :
IOManager.GetImageMapNormal();
}
Graphics graphic = Graphics.FromImage(backgroundLayer);
float b = SettingsMap.brightness / 100f;
// Apply grayscale color matrix, or just apply brightness adjustments
ColorMatrix matrix = SettingsMap.grayScale ?
new ColorMatrix(new float[][]
{
new float[] { 0.299f * b, 0.299f * b, 0.299f * b, 0, 0 },
new float[] { 0.587f * b, 0.587f * b, 0.587f * b, 0, 0 },
new float[] { 0.114f * b, 0.114f * b, 0.114f * b, 0, 0 },
new float[] { 0, 0, 0, 1, 0 },
new float[] { 0, 0, 0, 0, 1 },
}) :
new ColorMatrix(new float[][]
{
new float[] { b, 0, 0, 0, 0 },
new float[] { 0, b, 0, 0, 0 },
new float[] { 0, 0, b, 0, 0 },
new float[] { 0, 0, 0, 1, 0 },
new float[] { 0, 0, 0, 0, 1 },
});
ImageAttributes attributes = new ImageAttributes();
attributes.SetColorMatrix(matrix);
Point[] points =
{
new Point(0, 0),
new Point(mapDimension, 0),
new Point(0, mapDimension),
};
Rectangle rect = new Rectangle(0, 0, mapDimension, mapDimension);
graphic.DrawImage(backgroundLayer, points, rect, GraphicsUnit.Pixel, attributes);
Draw(); // Redraw the whole map since we updated the base layer
}
19
View Source File : Map.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
public static void Draw()
{
// Reset the current image to the background layer
finalImage = (Image)backgroundLayer.Clone();
Graphics imageGraphic = Graphics.FromImage(finalImage);
imageGraphic.SmoothingMode = SmoothingMode.AntiAlias;
Font font = new Font(fontCollection.Families[0], fontSize, GraphicsUnit.Pixel);
CellScaling cellScaling = null;
// Prepare the game version and watermark to be printed later
string infoText = (SettingsPlot.IsTopographic() ? "Topographic View\n" : string.Empty) + "Game version " + IOManager.GetGameVersion() + "\nMade with Mappalachia - github.com/AHeroicLlama/Mappalachia";
// Additional steps for cell mode (Add further text to watermark text, get cell height boundings)
if (SettingsMap.IsCellModeActive())
{
Cell currentCell = SettingsCell.GetCell();
// replacedign the CellScaling property
cellScaling = currentCell.GetScaling();
infoText =
currentCell.displayName + " (" + currentCell.editorID + ")\n" +
"Height distribution: " + SettingsCell.minHeightPerc + "% - " + SettingsCell.maxHeightPerc + "%\n" +
"Scale: 1:" + Math.Round(cellScaling.scale, 2) + "\n\n" +
infoText;
}
// Gather resources for drawing informational watermark text
Brush brushWhite = new SolidBrush(Color.White);
RectangleF infoTextBounds = new RectangleF(plotXMin, 0, mapDimension - plotXMin, mapDimension);
StringFormat stringFormatBottomRight = new StringFormat() { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Far }; // Align the text bottom-right
StringFormat stringFormatBottomLeft = new StringFormat() { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Far }; // Align the text bottom-left
// Draws bottom-right info text
imageGraphic.DrawString(infoText, font, brushWhite, infoTextBounds, stringFormatBottomRight);
// Draw a height-color key for Topography mode
if (SettingsPlot.IsTopographic())
{
// Identify the sizing and locations for drawing the height-color-key strings
double numHeightKeys = SettingsPlotTopograph.heightKeyIndicators;
Font topographFont = new Font(fontCollection.Families[0], 62, GraphicsUnit.Pixel);
float singleLineHeight = imageGraphic.MeasureString(SettingsPlotTopograph.heightKeyString, topographFont, new SizeF(infoTextBounds.Width, infoTextBounds.Height)).Height;
// Identify the lower limit to start printing the key so that it ends up centered
double baseHeight = (mapDimension / 2) - (singleLineHeight * (numHeightKeys / 2d));
for (int i = 0; i <= numHeightKeys - 1; i++)
{
Brush brush = new SolidBrush(GetTopographColor(i / (numHeightKeys - 1)));
imageGraphic.DrawString(SettingsPlotTopograph.heightKeyString, topographFont, brush, new RectangleF(plotXMax, 0, mapDimension - plotXMax, (float)(mapDimension - baseHeight)), stringFormatBottomRight);
baseHeight += singleLineHeight;
}
}
// Draw all legend text for every MapItem
int skippedLegends = DrawLegend(font, imageGraphic);
// Adds additional text if some items were missed from legend
if (skippedLegends > 0)
{
string extraLegendText = "+" + skippedLegends + " more item" + (skippedLegends == 1 ? string.Empty : "s") + "...";
imageGraphic.DrawString(extraLegendText, font, brushWhite, infoTextBounds, stringFormatBottomLeft);
}
// Start progress bar off at 0
progressBarMain.Value = progressBarMain.Minimum;
float progress = 0;
// Nothing else to plot - ensure we update for the background layer but then return
if (FormMaster.legendItems.Count == 0)
{
mapFrame.Image = finalImage;
return;
}
// Count how many Map Data Points are due to be mapped
int totalMapDataPoints = 0;
foreach (MapItem mapItem in FormMaster.legendItems)
{
totalMapDataPoints += mapItem.count;
}
// Loop through every MapDataPoint represented by all the MapItems to find the min/max z coord in the dataset
bool first = true;
int zMin = 0;
int zMax = 0;
double zRange = 0;
if (SettingsPlot.IsTopographic())
{
foreach (MapItem mapItem in FormMaster.legendItems)
{
foreach (MapDataPoint point in mapItem.GetPlots())
{
if (first)
{
zMin = point.z - (point.boundZ / 2);
zMax = point.z + (point.boundZ / 2);
first = false;
continue;
}
// Do not contribute outlier values to the min/max range - this ensures they have the same
// color as the min/max *legitimate* item and they do not skew the color ranges
if (point.z > SettingsPlotTopograph.zThreshUpper || point.z < SettingsPlotTopograph.zThreshLower)
{
continue;
}
if (point.z - (point.boundZ / 2) < zMin)
{
zMin = point.z - (point.boundZ / 2);
}
if (point.z + (point.boundZ / 2) > zMax)
{
zMax = point.z + (point.boundZ / 2);
}
}
}
zRange = Math.Abs(zMax - zMin);
if (zRange == 0)
{
zRange = 1;
}
}
if (SettingsPlot.IsIconOrTopographic())
{
if (SettingsPlot.IsTopographic())
{
// Somehow this line prevents a memory leak
// Without it, if drawing a large topographic map on first map draw, GC will not collect the multiple PlotIcon elements used in topographic drawing.
Application.DoEvents();
}
// Processing each MapItem in serial, draw plots for every matching valid MapDataPoint
foreach (MapItem mapItem in FormMaster.legendItems)
{
// Generate a Plot Icon and colours/brushes to be used for all instances of the MapItem
PlotIcon plotIcon = mapItem.GetIcon();
Image plotIconImg = SettingsPlot.IsIcon() ? plotIcon.GetIconImage() : null; // Icon mode has icon per MapItem, Topography needs icons per MapDataPoint and will be generated later
Color volumeColor = Color.FromArgb(volumeOpacity, plotIcon.color);
Brush volumeBrush = new SolidBrush(volumeColor);
// Iterate over every data point and draw it
foreach (MapDataPoint point in mapItem.GetPlots())
{
// Override colors in Topographic mode
if (SettingsPlot.IsTopographic())
{
// Clamp the z values to the percieved outlier threshold
double z = point.z + (point.boundZ / 2);
z = Math.Max(Math.Min(z, SettingsPlotTopograph.zThreshUpper), SettingsPlotTopograph.zThreshLower);
// Normalize the height of this item between the min/max z of the whole set
double colorValue = (z - zMin) / zRange;
// Override the plot icon color
plotIcon.color = GetTopographColor(colorValue);
plotIconImg = plotIcon.GetIconImage(); // Generate a new icon with a unique color for this height color
// Apply the color to volume plotting too
volumeColor = Color.FromArgb(volumeOpacity, plotIcon.color);
volumeBrush = new SolidBrush(volumeColor);
}
if (SettingsMap.IsCellModeActive())
{
// If this coordinate exceeds the user-selected cell mapping height bounds, skip it
// (Also accounts for the z-height of volumes)
if (point.z + (point.boundZ / 2d) < SettingsCell.GetMinHeightCoordBound() || point.z - (point.boundZ / 2d) > SettingsCell.GetMaxHeightCoordBound())
{
continue;
}
point.x += cellScaling.xOffset;
point.y += cellScaling.yOffset;
// Multiply the coordinates by the scaling, but multiply around 0,0
point.x = ((point.x - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
point.y = ((point.y - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
point.boundX *= cellScaling.scale;
point.boundY *= cellScaling.scale;
}
else // Skip the point if its origin is outside the surface world
if (point.x < plotXMin || point.x >= plotXMax || point.y < plotYMin || point.y >= plotYMax)
{
continue;
}
// If this meets all the criteria to be suitable to be drawn as a volume
if (point.primitiveShape != string.Empty && // This is a primitive shape at all
SettingsPlot.drawVolumes && // Volume drawing is enabled
point.boundX >= minVolumeDimension && point.boundY >= minVolumeDimension) // This is large enough to be visible if drawn as a volume
{
Image volumeImage = new Bitmap((int)point.boundX, (int)point.boundY);
Graphics volumeGraphic = Graphics.FromImage(volumeImage);
volumeGraphic.SmoothingMode = SmoothingMode.AntiAlias;
switch (point.primitiveShape)
{
case "Box":
case "Line":
case "Plane":
volumeGraphic.FillRectangle(volumeBrush, new Rectangle(0, 0, (int)point.boundX, (int)point.boundY));
break;
case "Sphere":
case "Ellipsoid":
volumeGraphic.FillEllipse(volumeBrush, new Rectangle(0, 0, (int)point.boundX, (int)point.boundY));
break;
default:
continue; // If we reach this, we dropped the drawing of a volume. Verify we've covered all shapes via the database summary.txt
}
volumeImage = ImageTools.RotateImage(volumeImage, point.rotationZ);
imageGraphic.DrawImage(volumeImage, (float)(point.x - (volumeImage.Width / 2)), (float)(point.y - (volumeImage.Height / 2)));
}
// This MapDataPoint is not suitable to be drawn as a volume - draw a normal plot icon, or topographic plot
else
{
imageGraphic.DrawImage(plotIconImg, (float)(point.x - (plotIconImg.Width / 2d)), (float)(point.y - (plotIconImg.Height / 2d)));
}
}
// Increment the progress bar per MapItem
progress += mapItem.count;
progressBarMain.Value = (int)((progress / totalMapDataPoints) * progressBarMain.Maximum);
Application.DoEvents();
}
}
else if (SettingsPlot.IsHeatmap())
{
int resolution = SettingsPlotHeatmap.resolution;
int blendRange = SettingsPlotHeatmap.blendDistance;
// Create a 2D Array of HeatMapGridSquare
HeatMapGridSquare[,] squares = new HeatMapGridSquare[resolution, resolution];
for (int x = 0; x < resolution; x++)
{
for (int y = 0; y < resolution; y++)
{
squares[x, y] = new HeatMapGridSquare();
}
}
int pixelsPerSquare = mapDimension / resolution;
foreach (MapItem mapItem in FormMaster.legendItems)
{
int heatmapLegendGroup = SettingsPlotHeatmap.IsDuo() ? mapItem.legendGroup % 2 : 0;
foreach (MapDataPoint point in mapItem.GetPlots())
{
if (SettingsMap.IsCellModeActive())
{
point.x += cellScaling.xOffset;
point.y += cellScaling.yOffset;
point.x = ((point.x - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
point.y = ((point.y - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
}
// Identify which grid square this MapDataPoint falls within
int squareX = (int)Math.Floor(point.x / pixelsPerSquare);
int squareY = (int)Math.Floor(point.y / pixelsPerSquare);
// Loop over every grid square within range, and increment by the weight proportional to the distance
for (int x = squareX - blendRange; x < squareX + blendRange; x++)
{
for (int y = squareY - blendRange; y < squareY + blendRange; y++)
{
// Don't try to target squares which would lay outside of the grid
if (x < 0 || x >= resolution || y < 0 || y >= resolution)
{
continue;
}
// Pythagoras on the x and y dist gives us the 'as the crow flies' distance between the squares
double distance = Pythagoras(squareX - x, squareY - y);
// Weight and hence brightness is modified by 1/x^2 + 1 where x is the distance from actual item
double additionalWeight = point.weight * (1d / ((distance * distance) + 1));
squares[x, y].weights[heatmapLegendGroup] += additionalWeight;
}
}
}
// Increment the progress bar per MapItem
progress += mapItem.count;
progressBarMain.Value = (int)((progress / totalMapDataPoints) * progressBarMain.Maximum);
Application.DoEvents();
}
// Find the largest weight value of all squares
double largestWeight = 0;
for (int x = 0; x < resolution; x++)
{
for (int y = 0; y < resolution; y++)
{
double weight = squares[x, y].GetTotalWeight();
if (weight > largestWeight)
{
largestWeight = weight;
}
}
}
// Finally now weights are calculated, draw a square for every HeatGripMapSquare in the array
for (int x = 0; x < resolution; x++)
{
int xCoord = x * pixelsPerSquare;
// Don't draw grid squares which are entirely within the legend text area
if (xCoord + pixelsPerSquare < plotXMin)
{
continue;
}
for (int y = 0; y < resolution; y++)
{
int yCoord = y * pixelsPerSquare;
Color color = squares[x, y].GetColor(largestWeight);
Brush brush = new SolidBrush(color);
Rectangle heatMapSquare = new Rectangle(xCoord, yCoord, mapDimension / SettingsPlotHeatmap.resolution, mapDimension / SettingsPlotHeatmap.resolution);
imageGraphic.FillRectangle(brush, heatMapSquare);
}
}
}
mapFrame.Image = finalImage;
}
19
View Source File : Map.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
License : GNU General Public License v3.0
Project Creator : AHeroicLlama
static void DrawCellBackground(Graphics backgroundLayer)
{
if (!SettingsMap.IsCellModeActive())
{
return;
}
CellScaling cellScaling = SettingsCell.GetCell().GetScaling();
int outlineWidth = SettingsCell.outlineWidth;
int outlineSize = SettingsCell.outlineSize;
Image plotIconImg = new Bitmap(outlineSize, outlineSize);
Graphics plotIconGraphic = Graphics.FromImage(plotIconImg);
plotIconGraphic.SmoothingMode = SmoothingMode.AntiAlias;
Color outlineColor = Color.FromArgb(SettingsCell.outlineAlpha, SettingsCell.outlineColor);
Pen outlinePen = new Pen(outlineColor, outlineWidth);
plotIconGraphic.DrawEllipse(
outlinePen,
new RectangleF(outlineWidth, outlineWidth, outlineSize - (outlineWidth * 2), outlineSize - (outlineWidth * 2)));
// Iterate over every data point and draw it
foreach (MapDataPoint point in DataHelper.GetAllCellCoords(SettingsCell.GetCell().formID))
{
// If this coordinate exceeds the user-selected cell mapping height bounds, skip it
// (Also accounts for the z-height of volumes)
if (point.z < SettingsCell.GetMinHeightCoordBound() || point.z > SettingsCell.GetMaxHeightCoordBound())
{
continue;
}
point.x += cellScaling.xOffset;
point.y += cellScaling.yOffset;
// Multiply the coordinates by the scaling, but multiply around 0,0
point.x = ((point.x - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
point.y = ((point.y - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
point.boundX *= cellScaling.scale;
point.boundY *= cellScaling.scale;
backgroundLayer.DrawImage(plotIconImg, (float)(point.x - (plotIconImg.Width / 2d)), (float)(point.y - (plotIconImg.Height / 2d)));
}
GC.Collect();
}
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 Image DecodeAsThumbnail()
{
if (_thumbnailCache == null)
{
Image image = Decode();
int thumbWidth = ThumbnailSize;
int thumbHeight = ThumbnailSize;
if (Width > Height)
{
thumbHeight = (int)Math.Ceiling(((float) Height/Width)*ThumbnailSize);
}
else if (Height > Width)
{
thumbWidth = (int)Math.Ceiling(((float) Width/Height)*ThumbnailSize);
}
if (Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1)
{
// for Windows 7
// Don't use GetThumbnailImage as GDI+ is bugged.
_thumbnailCache = new Bitmap(thumbWidth, thumbHeight);
using (var g = Graphics.FromImage(_thumbnailCache))
{
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
g.DrawImage(image, 0, 0, thumbWidth, thumbHeight);
}
}
else
{
_thumbnailCache = image.GetThumbnailImage(thumbWidth, thumbHeight, () => false, IntPtr.Zero);
}
}
return _thumbnailCache;
}
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 : Graphics.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public osf.Graphics FromImage(osf.Image p1)
{
Graphics Graphics1 = new Graphics(System.Drawing.Graphics.FromImage(p1.M_Image));
System.Windows.Forms.Application.DoEvents();
return Graphics1;
}
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 : 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 : 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 Image ShortColorImage(Image srcImage)
{
Debug.replacedert(srcImage != null && srcImage.PixelFormat == PixelFormat.Format32bppArgb);
Bitmap bmp = new Bitmap(srcImage.Width, srcImage.Height, PixelFormat.Format16bppRgb555);
using (Graphics g = Graphics.FromImage(bmp))
{
g.DrawImage(srcImage, 0, 0);
}
return bmp;
}
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 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
View Source File : CompressStorage.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private void CompressImageData(Snapshot sshot)
{
Debug.replacedert(sshot.ImageData != null && sshot.ImageData.Length > 0);
Debug.replacedert(sshot.BackgroundId == null);
try
{
Image img = null;
using (MemoryStream ms = new MemoryStream(sshot.ImageData))
img = Image.FromStream(ms);
Debug.replacedert(img.PixelFormat != PixelFormat.Format8bppIndexed);
if (_backgroundImage == null)
{
_backgroundId = sshot.SnapshotId;
_backgroundImage = img;
}
else
{
Debug.replacedert(_backgroundImage != null && _backgroundImage != img);
Debug.replacedert(_backgroundImage.PixelFormat == img.PixelFormat);
Rectangle rc = CompareImageDifference(_backgroundImage, img);
if (rc.Width * rc.Height * 100 / img.Width * img.Height > 80)
{
// change background.
_backgroundId = sshot.SnapshotId;
_backgroundImage = img;
}
else
{
// clip
Bitmap bmp = new Bitmap(rc.Width, rc.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.DrawImage(img, 0, 0, rc, GraphicsUnit.Pixel);
}
sshot.BackgroundId = _backgroundId;
sshot.WindowRect = rc;
using (MemoryStream ms = new MemoryStream())
{
bmp.Save(ms, ImageFormat.Png);
sshot.ImageData = ms.ToArray();
}
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
}
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 : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : 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
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 Bitmap ColorValueBitmap(Image img)
{
int width = img.Width;
int height = img.Height;
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format16bppRgb555);
using (Graphics g = Graphics.FromImage(bmp))
{
g.PageUnit = GraphicsUnit.Pixel;
g.DrawImage(img, 0, 0);
}
return bmp;
}
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 : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : 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
View Source File : ImageMaker.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
internal byte[] GetImageBytes(params ImageMakerLayer[] imageLayers)
{
Bitmap bitmap = new Bitmap(ImageSizeX, ImageSizeY);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.Clear(BackgroundColor);
// Draw all layers of the image
foreach (ImageMakerLayer layer in imageLayers)
{
string filePath = $"{BRPaths.INCLUDE_JPG}{layer.FileName}";
if (!File.Exists(filePath)) continue; // File doesn't exist, ignore it.
using (Image layerImage = Image.FromFile(filePath))
{
Point position = GetImagePosition(layer, layerImage.Size);
RotateGraphics(graphics, layer.Rotation);
graphics.DrawImage(layerImage,
new Rectangle(position, new Size((int)(layerImage.Size.Width * layer.Scale), (int)(layerImage.Size.Height * layer.Scale))),
new Rectangle(Point.Empty, layerImage.Size),
GraphicsUnit.Pixel);
RotateGraphics(graphics, -layer.Rotation);
}
}
// Draw the text overlay
TextOverlay.Draw(graphics);
}
// Coverts the image to a JPG and get all bytes
byte[] bytes;
using (var ms = new MemoryStream())
{
bitmap.Save(ms, ImageFormat.Jpeg);
bytes = ms.ToArray();
}
return bytes;
}
19
View Source File : DynamicTextImage.cs
License : MIT License
Project Creator : akasarto
License : MIT License
Project Creator : akasarto
public MemoryStream Build(string text)
{
text = text ?? "?";
var stream = new MemoryStream();
var backgroundColor = ColorTranslator.FromHtml($"#{_backgroundHexColor.Trim('#')}");
var foreGroundColor = ColorTranslator.FromHtml($"#{_foregroundHexColor.Trim('#')}");
using (var baseFont = _fontInstanceCreator())
{
using (var bitmap = new Bitmap(_width, _height, PixelFormat.Format24bppRgb))
{
using (var graphics = Graphics.FromImage(bitmap))
{
var textSize = graphics.MeasureString(text, baseFont);
var fontScale = Math.Max(textSize.Width / bitmap.Width, textSize.Height / bitmap.Height);
using (var scaledFont = new Font(baseFont.FontFamily, baseFont.SizeInPoints / fontScale, baseFont.Style, baseFont.Unit))
{
graphics.Clear(backgroundColor);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
StringFormat strinngFormat = new StringFormat(StringFormat.GenericTypographic)
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center,
FormatFlags = StringFormatFlags.MeasureTrailingSpaces
};
textSize = graphics.MeasureString(text, scaledFont);
graphics.DrawString(
text,
scaledFont,
new SolidBrush(foreGroundColor),
new RectangleF(
0,
0,
bitmap.Width,
bitmap.Height
),
strinngFormat
);
bitmap.Save(stream, ImageFormat.Png);
stream.Position = 0;
}
}
}
}
return stream;
}
19
View Source File : TestDownloader.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
private byte[] ApplyText(byte[] img, string modelName)
{
using (var ms = new MemoryStream(img))
{
var bmp = Image.FromStream(ms);
var g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
var fSize = bmp.Height / 30;
var f = GetAdjustedFont(g, modelName, new Font("Arial", fSize), fSize);
var textPosition = new Point(bmp.Height / 30, (bmp.Height / 30) * 29);
var size = g.MeasureString(modelName, f);
var rect = new RectangleF(textPosition.X, textPosition.Y, size.Width, size.Height);
g.FillRectangle(Brushes.Black, rect);
g.DrawString(modelName, f, Brushes.LightGray, textPosition);
g.Flush();
using (var msOut = new MemoryStream())
{
bmp.Save(msOut, System.Drawing.Imaging.ImageFormat.Jpeg);
return msOut.ToArray();
}
}
}
19
View Source File : BitmapExtensions.cs
License : MIT License
Project Creator : AlexanderPro
License : MIT License
Project Creator : AlexanderPro
public static Bitmap Grayscale(this Bitmap bitmap)
{
var newBitmap = new Bitmap(bitmap.Width, bitmap.Height);
using (var graphics = Graphics.FromImage(newBitmap))
using (var attributes = new ImageAttributes())
{
var colorMatrix = new ColorMatrix(
new float[][]
{
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
attributes.SetColorMatrix(colorMatrix);
graphics.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, attributes);
return newBitmap;
}
}
19
View Source File : BitmapExtensions.cs
License : MIT License
Project Creator : AlexanderPro
License : MIT License
Project Creator : AlexanderPro
public static Bitmap Pixelate(this Bitmap bitmap, int pixelateSize)
{
var newBitmap = new Bitmap(bitmap.Width, bitmap.Height);
// make an exact copy of the bitmap provided
using (var graphics = Graphics.FromImage(newBitmap))
{
graphics.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
}
// look at every pixel in the rectangle while making sure we're within the bitmap bounds
for (var xx = 0; xx < newBitmap.Width; xx += pixelateSize)
{
for (var yy = 0; yy < newBitmap.Height; yy += pixelateSize)
{
var offsetX = pixelateSize / 2;
var offsetY = pixelateSize / 2;
// make sure that the offset is within the boundry of the bitmap
while (xx + offsetX >= newBitmap.Width) offsetX--;
while (yy + offsetY >= newBitmap.Height) offsetY--;
// get the pixel color in the center of the soon to be newBitmap area
var pixel = newBitmap.GetPixel(xx + offsetX, yy + offsetY);
// for each pixel in the pixelate size, set it to the center color
for (var x = xx; x < xx + pixelateSize && x < bitmap.Width; x++)
{
for (var y = yy; y < yy + pixelateSize && y < bitmap.Height; y++)
{
newBitmap.SetPixel(x, y, pixel);
}
}
}
}
return newBitmap;
}
19
View Source File : BitmapExtensions.cs
License : MIT License
Project Creator : AlexanderPro
License : MIT License
Project Creator : AlexanderPro
public static Bitmap Copy(this Bitmap bitmap)
{
var newBitmap = new Bitmap(bitmap.Width, bitmap.Height);
// make an exact copy of the bitmap provided
using (var graphics = Graphics.FromImage(newBitmap))
{
graphics.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
}
return newBitmap;
}
19
View Source File : WindowUtils.cs
License : MIT License
Project Creator : AlexanderPro
License : MIT License
Project Creator : AlexanderPro
public static Bitmap PrintWindow(IntPtr hwnd)
{
Rect rect;
GetWindowRect(hwnd, out rect);
var bitmap = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
using (var graphics = Graphics.FromImage(bitmap))
{
var hdc = graphics.GetHdc();
NativeMethods.PrintWindow(hwnd, hdc, 0);
graphics.ReleaseHdc(hdc);
}
return bitmap;
}
19
View Source File : BitmapExtensions.cs
License : MIT License
Project Creator : AlexanderPro
License : MIT License
Project Creator : AlexanderPro
public static Bitmap Dark(this Bitmap bitmap)
{
var newBitmap = new Bitmap(bitmap.Width, bitmap.Height);
using (var graphics = Graphics.FromImage(newBitmap))
{
graphics.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
var brush = new SolidBrush(Color.FromArgb(200, 0, 0, 0));
graphics.FillRectangle(brush, 0, 0, bitmap.Width, bitmap.Height);
}
return newBitmap;
}
19
View Source File : BitmapExtensions.cs
License : MIT License
Project Creator : AlexanderPro
License : MIT License
Project Creator : AlexanderPro
public static Bitmap BlackAndWhite(this Bitmap bitmap)
{
var newBitmap = new Bitmap(bitmap.Width, bitmap.Height);
using (var graphics = Graphics.FromImage(newBitmap))
{
graphics.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
}
for (var x = 0; x < newBitmap.Width; x++)
{
for (var y = 0; y < newBitmap.Height; y++)
{
var pixel = newBitmap.GetPixel(x, y);
var avg = (pixel.R + pixel.G + pixel.B) / 3;
newBitmap.SetPixel(x, y, Color.FromArgb(avg, avg, avg));
}
}
return newBitmap;
}
19
View Source File : WindowUtils.cs
License : MIT License
Project Creator : AlexanderPro
License : MIT License
Project Creator : AlexanderPro
public static Bitmap PrintWindow(IntPtr hWnd)
{
Rect rect;
NativeMethods.GetWindowRect(hWnd, out rect);
var bitmap = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
using (var graphics = Graphics.FromImage(bitmap))
{
var hdc = graphics.GetHdc();
NativeMethods.PrintWindow(hWnd, hdc, 0);
graphics.ReleaseHdc(hdc);
}
return bitmap;
}
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
public static void CopyAsImage(IPrintable doreplacedent, bool selectedOnly)
{
if (doreplacedent == null)
throw new ArgumentNullException("doreplacedent");
RectangleF areaF = doreplacedent.GetPrintingArea(true);
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));
using (Bitmap image = new Bitmap(area.Width, area.Height, PixelFormat.Format24bppRgb))
using (Graphics g = Graphics.FromImage(image))
{
// Set drawing parameters
g.SmoothingMode = SmoothingMode.HighQuality;
if (DiagramEditor.Settings.Default.UseClearTypeForImages)
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
else
g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
g.TranslateTransform(-area.Left, -area.Top);
// Draw image
g.Clear(Style.CurrentStyle.BackgroundColor);
IGraphics graphics = new GdiGraphics(g);
doreplacedent.Print(graphics, selectedOnly, Style.CurrentStyle);
try
{
System.Windows.Forms.Clipboard.SetImage(image);
}
catch
{
//UNDONE: exception handling of CopyAsImage()
}
}
}
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 : 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 : TreeColumn.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
internal Bitmap CreateGhostImage(Rectangle bounds, Font font)
{
Bitmap b = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
Graphics gr = Graphics.FromImage(b);
gr.FillRectangle(SystemBrushes.ControlDark, bounds);
DrawContent(gr, bounds, font);
BitmapHelper.SetAlphaChanelValue(b, 150);
return b;
}
19
View Source File : TreeViewAdv.Draw.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public void AutoSizeColumn(TreeColumn column)
{
if (!Columns.Contains(column))
throw new ArgumentException("column");
DrawContext context = new DrawContext();
context.Graphics = Graphics.FromImage(new Bitmap(1, 1));
context.Font = this.Font;
int res = 0;
for (int row = 0; row < RowCount; row++)
{
if (row < RowMap.Count)
{
int w = 0;
TreeNodeAdv node = RowMap[row];
foreach (NodeControl nc in NodeControls)
{
if (nc.ParentColumn == column)
w += nc.GetActualSize(node, _measureContext).Width;
}
res = Math.Max(res, w);
}
}
if (res > 0)
column.Width = res;
}
See More Examples