How can I introduce an overlay on an image - c#

How can I manipulate images to add a semi-transparent 1x1 checked overlay like the second image in C#?

I was able to modify an answer I posted a while ago and create the overlay in code. After the overlay image is created, I use a TextureBrush to fill the area of the original image. The settings in the code below created the following image; you can change the size and colors to suit your needs.
// set the light and dark overlay colors
Color c1 = Color.FromArgb(80, Color.Silver);
Color c2 = Color.FromArgb(80, Color.DarkGray);
// set up the tile size - this will be 8x8 pixels, with each light/dark square being 4x4 pixels
int length = 8;
int halfLength = length / 2;
using (Bitmap overlay = new Bitmap(length, length, PixelFormat.Format32bppArgb))
{
// draw the overlay - this will be a 2 x 2 grid of squares,
// alternating between colors c1 and c2
for (int x = 0; x < length; x++)
{
for (int y = 0; y < length; y++)
{
if ((x < halfLength && y < halfLength) || (x >= halfLength && y >= halfLength))
overlay.SetPixel(x, y, c1);
else
overlay.SetPixel(x, y, c2);
}
}
// open the source image
using (Image image = Image.FromFile(#"C:\Users\Public\Pictures\Sample Pictures\homers_brain.jpg"))
using (Graphics graphics = Graphics.FromImage(image))
{
// create a brush from the overlay image, draw over the source image and save to a new image
using (Brush overlayBrush = new TextureBrush(overlay))
{
graphics.FillRectangle(overlayBrush, new Rectangle(new Point(0, 0), image.Size));
image.Save(#"C:\Users\Public\Pictures\Sample Pictures\homers_brain_overlay.jpg");
}
}
}

Load your original image in to a system.Drawing.Image, then create a graphics object from it. Load your 2nd image of the checker pattern you want to draw, and use the graphics object you created to repeatedly draw the checker image over the original image.
Untested Example
Image Original;
Image Overlay;
Original = new Bitmap(100, 100, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //Load your real image here.
Overlay = new Bitmap(2, 2 ,System.Drawing.Imaging.PixelFormat.Format32bppArgb);//Load your 2x2 (or whatever size you want) overlay image here.
Graphics gr = Graphics.FromImage(Original);
for (int y = 0; y < Original.Height + Overlay.Height; y = y + Overlay.Height)
{
for (int x = 0; x < Original.Width + OverlayWidth; x = x + Overlay.Width)
{
gr.DrawImage(Overlay, x, y);
}
}
gr.Dispose();
After the code executes, Original will now contain the Original image with the overlay applied to it.

Related

Custom Measure String in C# without Graphics.MeasureString

I am trying to create an Image with a Caption/Text on it for Youtube-Thumbnails.
Following Rules are defined:
The Text is the Title of the Video and always changes from Thumbnail to Thumbnail.
The Porgram uses a pre-defined Text-Width which must not be touched by the Text on the Image.
The Text should be as close to the pre-defined with as possible.
So my thoughts were that I would use Graphics.MeasureString to be able to track the Width of the String on the Image and increase the Font-Size and repeat this until the pre-defined Width is closely reached but not touched.
But I have tested it with MeasureString and found out that it isn't that accurate. And also found confirmation here: Graphics.MeasureCharacterRanges giving wrong size calculations
I have tried the things they have recommended but with no success as the final width of my string always overflooded the image borders. Even if my pre-defined Width was way smaller than the Image Width. (Image Width: 1920; Pre-Defined Width: 1600)
So I came up with the Idea to create a custom Measurement Method and to write the String as I want it on a new Bitmap and to count the maximum Pixels of the String in Height and Width. (The Height is just for future stuff)
My current Code is:
public static SizeF MeasuredStringSize(string text, Bitmap originBitmap, FontFamily fontFamily, StringFormat strformat)
{
int currentFontSize = 10;
SizeF measuredSize = new();
var highestWidth = 0;
var highestHeight = 0;
while (highestWidth < maximumTextWidth)
{
Bitmap bitmap = new(originBitmap);
Bitmap _bitmap = new(bitmap.Width, bitmap.Height);
using Graphics graphics = Graphics.FromImage(bitmap);
if (graphics != null)
{
graphics.TranslateTransform(bitmap.Width / 2, bitmap.Height / 2);
currentFontSize++;
graphics.Clear(Color.White);
using GraphicsPath path = new();
using SolidBrush brush = new(Color.Red);
using Pen pen = new(Color.Red, 6)
{
LineJoin = LineJoin.Round
};
path.AddString(text, fontFamily, (int)fontStyle, currentFontSize, new Point(0, 0), strformat);
graphics.DrawPath(pen, path);
graphics.FillPath(brush, path);
Dictionary<int, List<int>> redPixelMatrix = new();
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
var currentPixelColor = bitmap.GetPixel(i, j);
if (currentPixelColor.B != 255 && currentPixelColor.G != 255 && currentPixelColor.R == 255)
{
if (!redPixelMatrix.ContainsKey(i))
{
redPixelMatrix.Add(i, new());
}
redPixelMatrix[i].Add(j);
}
}
}
highestWidth = redPixelMatrix.Keys.Count;
highestHeight = redPixelMatrix.Aggregate((l, r) => l.Value.Count > r.Value.Count ? l : r).Value.Count;
Console.WriteLine($"X:{highestWidth};Y:{highestHeight}");
//Debugging the final Image with Text to see the Result
bitmap.Save(ResultPath);
}
}
measuredSize = new SizeF(highestWidth, highestHeight);
return measuredSize;
}
The Resulting Image from bitmap.Save(ResultPath); as the String reaches the Image borders looks like this:
But the exact String width is 1742 instead of the width of my Image 1920 which should be more or less the same at this moment.
So, why is the Text nearly as wide as the Image but doesn't have the same width?
highestWidth = redPixelMatrix.Keys.Count; This will just count the number of columns containing red pixels, excluding any spaces in the text. You presumably want the minimum and maximum indices.
I.e.
var minX = int.MaxValue;
var maxX = int.MinValue;
// Loops over rows & columns
// Check if pixel is red
if(i > maxX) maxX = i;
if(i < minX) minX = i;
If you only want the text width and not the bounds you can just do maxX - minX.

How to draw what is inside a contour in an image but leave everything else blank?

I have a colour image of type Image<Hsv, Byte>, and another image of type Image<Gray, Byte> of the same size that is all black with some all-white shapes. From the black and white image, I found the contours of the shapes using findContours(). What I want is to create a new image or modify the original colour image I have to show only what corresponds to inside the contours, with everything else being transparent, without having to check pixel by pixel values of the two images (did this, it takes too long). Any possible way to do this?
For example, I have the original image, the black and white image, and the final product I need.
I'm completely new to emgucv, so, I'm not saying this is the best approach; but it seems to work.
Create a new draw surface
Draw the original image
Change the white pixels in the mask image to transparent pixels
Draw the transparent mask on top of the original image
The result image looks like your desired outcome.
void Main()
{
var path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"images");
var original = new Image<Bgr, Byte>(Path.Combine(path, "vz7Oo1W.png"));
var mask = new Image<Bgr, Byte>(Path.Combine(path, "vIQUvUU.png"));
var bitmap = new Bitmap(original.Width, original.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.DrawImage(original.Bitmap, 0, 0);
g.DrawImage(MakeTransparent(mask.Bitmap), 0, 0);
}
bitmap.Save(Path.Combine(path, "new.png"));
}
public static Bitmap MakeTransparent(Bitmap image)
{
Bitmap b = new Bitmap(image);
var tolerance = 10;
for (int i = b.Size.Width - 1; i >= 0; i--)
{
for (int j = b.Size.Height - 1; j >= 0; j--)
{
var col = b.GetPixel(i, j);
col.Dump();
if (255 - col.R < tolerance &&
255 - col.G < tolerance &&
255 - col.B < tolerance)
{
b.SetPixel(i, j, Color.Transparent);
}
}
}
return b;
}

Get grayscale Image height without considering white pixels

I have grayscale pictures of an ArrayList<System.Windows.Controls.Image> laid out horizontally on a Canvas. Their ImageSource are of type System.Windows.Media.Imaging.BitmapImage.
Is there a way to measure in pixels the height of each Image without considering white, non-transparent pixels Outside the colored part ?
Lets say I have an Image of height 10, in which the whole top half is white and the bottom half is black; I would need to get 5 as it's height. In the same way, if that Image had the top third black, middle third white and bottom third black, the height would be 10.
Here's a drawing that shows the desired heights (in blue) of 3 images:
I am willing to use another type for the images, but it Must be possible to either get from a byte[] array to that type, or to convert Image to it.
I have read the docs on Image, ImageSource and Visual, but I really have no clue where to start.
Accessing pixel data from a BitmapImage is a bit of a hassle, but you can construct a WriteableBitmap from the BitmapImage object which is much easier (not to mention more efficient).
WriteableBitmap bmp = new WriteableBitmap(img.Source as BitmapImage);
bmp.Lock();
unsafe
{
int width = bmp.PixelWidth;
int height = bmp.PixelHeight;
byte* ptr = (byte*)bmp.BackBuffer;
int stride = bmp.BackBufferStride;
int bpp = 4; // Assuming Bgra image format
int hms;
for (int y = 0; y < height; y++)
{
hms = y * stride;
for (int x = 0; x < width; x++)
{
int idx = hms + (x * bpp);
byte b = ptr[idx];
byte g = ptr[idx + 1];
byte r = ptr[idx + 2];
byte a = ptr[idx + 3];
// Construct your histogram
}
}
}
bmp.Unlock();
From here, you can construct a histogram from the pixel data, and analyze that histogram to find the boundaries of the non-white pixels in the images.
EDIT: Here's a Silverlight solution:
public static int getNonWhiteHeight(this Image img)
{
WriteableBitmap bmp = new WriteableBitmap(img.Source as BitmapImage);
int topWhiteRowCount = 0;
int width = bmp.PixelWidth;
int height = bmp.PixelHeight;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int pixel = bmp.Pixels[y * width + x];
if (pixel != -1)
{
topWhiteRowCount = y - 1;
goto returnLbl;
}
}
}
returnLbl:
return topWhiteRowCount >= 0 ? height - topWhiteRowCount : height;
}

shadow getting darker drawn on bitmap

I'm trying to create a shadow to a rectangle drawn dynamically on a bitmap. The problem is the shadow gets darker each time I draw a new rectangle (please see screenshot). I suspect that the same bitmap is used to draw the new rectangles. I tried using Graphics.clear() but it cleans the screen which I don't want. How can solve this problem?
Here is the code which draws the shadow:
public void drawAll(Rectangle baseRect,Graphics g)
{
int shadWidth = 10;
Bitmap bm = new Bitmap(shadWidth, baseRect.Height+shadWidth);//baseRect is created dynamically
for (int y = 0; y < baseRect.Height + shadWidth; y++)
{
int factor = 255 / shadWidth;//255 is the alpha color divided over the shadow width
int alpha = 255;
for (int x = 0; x < shadWidth; x++)
{
alpha -= factor;
if (alpha < 0) alpha = 0;
Color transColr = Color.FromArgb(alpha, 0, 0, 0);
bm.SetPixel(x, y, transColr);
}
}
GraphicsPath path = new GraphicsPath();
PointF[] pts = new[] {new PointF(baseRect.Right, baseRect.Top),
new PointF(baseRect.Right+shadWidth, baseRect.Top+shadWidth),
new PointF(baseRect.Right+shadWidth, baseRect.Bottom+shadWidth),
new PointF(baseRect.Right, baseRect.Bottom),
new PointF(baseRect.Right, baseRect.Top)};
path.AddLines(pts);
SmoothingMode old = g.SmoothingMode;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.DrawImageUnscaled(bm, baseRect.Right, baseRect.Y);
}

C# - Crop Transparent/White space

I'm trying to remove all white or transparent pixels from an image, leaving the actual image (cropped). I've tried a few solutions, but none seem to work. Any suggestions or am I going to spend the night writing image cropping code?
So, what you want to do is find the top, left most non white/transparent pixel and the bottom, right most non white/transparent pixel. These two coordinates will give you a rectangle that you can then extract.
// Load the bitmap
Bitmap originalBitmap = Bitmap.FromFile("d:\\temp\\test.bmp") as Bitmap;
// Find the min/max non-white/transparent pixels
Point min = new Point(int.MaxValue, int.MaxValue);
Point max = new Point(int.MinValue, int.MinValue);
for (int x = 0; x < originalBitmap.Width; ++x)
{
for (int y = 0; y < originalBitmap.Height; ++y)
{
Color pixelColor = originalBitmap.GetPixel(x, y);
if (!(pixelColor.R == 255 && pixelColor.G == 255 && pixelColor.B == 255)
|| pixelColor.A < 255)
{
if (x < min.X) min.X = x;
if (y < min.Y) min.Y = y;
if (x > max.X) max.X = x;
if (y > max.Y) max.Y = y;
}
}
}
// Create a new bitmap from the crop rectangle
Rectangle cropRectangle = new Rectangle(min.X, min.Y, max.X - min.X, max.Y - min.Y);
Bitmap newBitmap = new Bitmap(cropRectangle.Width, cropRectangle.Height);
using (Graphics g = Graphics.FromImage(newBitmap))
{
g.DrawImage(originalBitmap, 0, 0, cropRectangle, GraphicsUnit.Pixel);
}
public Bitmap CropBitmap(Bitmap original)
{
// determine new left
int newLeft = -1;
for (int x = 0; x < original.Width; x++)
{
for (int y = 0; y < original.Height; y++)
{
Color color = original.GetPixel(x, y);
if ((color.R != 255) || (color.G != 255) || (color.B != 255) ||
(color.A != 0))
{
// this pixel is either not white or not fully transparent
newLeft = x;
break;
}
}
if (newLeft != -1)
{
break;
}
// repeat logic for new right, top and bottom
}
Bitmap ret = new Bitmap(newRight - newLeft, newTop - newBottom);
using (Graphics g = Graphics.FromImage(ret)
{
// copy from the original onto the new, using the new coordinates as
// source coordinates for the original
g.DrawImage(...);
}
return ret
}
Note that this function will be slow as dirt. GetPixel() is unbelievably slow, and accessing the Width and Height properties of a Bitmap inside a loop is also slow. LockBits would be the proper way to do this - there are tons of examples here on StackOverflow.
Per-pixel check should do the trick. Scan each line to find empty line from the top & bottom, scan each row to find left & right constraints (this can be done in one pass with either rows or columns). When the constraint is found - copy the part of the image to another buffer.
In WPF we have a WriteableBitmap class. Is this what are you looking for ? If it is the case please have a look at http://blogs.msdn.com/b/jgalasyn/archive/2008/04/17/using-writeablebitmap-to-display-a-procedural-texture.aspx
I found a method to batch trim a few thousand .jpg files in about 10 minutes, but I didn't do it in code. I used the Convert feature of Snag-It Editor. I don't know if this is an option for you, if you need to do this trimming once or your need is ongoing, but for the price of the software, which isn't a whole lot, I considered this a decent workaround.
(I do not work for or represent Techsmith.)
Joey
Adding to this, if you are in WPF and you have excess space around your image, check the properties of the image and make sure your Stretch property is set to fill. This eliminated the space around the image.
Screen shot of the property in WPF

Categories