Add text to image using AForge.Video.FFMEG in C# - c#

Using AForge.Video.FFMPEG I am able to create video from Images.
string[] files;
string folderPath = #"FolderPath";
files = Directory.GetFiles(folderPath).OrderBy(c => c).ToArray();
VideoFileWriter writer = new VideoFileWriter();
writer.Open(#"C:folder\new.mp4", imageWidth, imageHeight, 10, VideoCodec.MPEG4);
for (int j = 0; j < files.Length; j++)
{
string fileName = files[j];
BitmapSource imageBitMap = new BitmapImage(new Uri(fileName, UriKind.RelativeOrAbsolute));
imageBitMap.Freeze();
int stride = imageBitMap.PixelWidth * ((imageBitMap.Format.BitsPerPixel + 7) / 8);
byte[] ImageInBits = new byte[imageBitMap.PixelWidth * imageBitMap.PixelHeight];
imageBitMap.CopyPixels(ImageInBits, stride, 0);
Bitmap image = new Bitmap(imageWidth, imageHeight, stride, PixelFormat.Format8bppIndexed, Marshal.UnsafeAddrOfPinnedArrayElement(ImageInBits, 0));
writer.WriteVideoFrame(image);
image.Dispose();
}
I am trying to add text/String to input image using
private Bitmap WriteString(Bitmap bmp)
{
RectangleF rectf = new RectangleF(70, 90, 90, 50);
Bitmap tempBitmap = new Bitmap(bmp.Width, bmp.Height);
Graphics g = Graphics.FromImage(tempBitmap);
g.DrawImage(bmp, 0, 0);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma", 8), Brushes.Red, rectf);
g.Flush();
return bmp;
}
like
Bitmap image = new Bitmap(imageWidth, imageHeight, stride, PixelFormat.Format8bppIndexed, Marshal.UnsafeAddrOfPinnedArrayElement(ImageInBits, 0));
Bitmap outputBitmap=WriteString(image);
writer.WriteVideoFrame(outputBitmap);
How can I write a string to Image?
Is there any way to add subtitle to AForge.Video.FFMEG to image before creating video?

private Bitmap WriteString(Bitmap bmp) {
Bitmap tempBitmap = new Bitmap(bmp.Width, bmp.Height); << create new
..draw on copy..
return bmp; <<< return original
}
Seems to be the wrong.

Related

How to set a 200x200 background of an image?

I am currently creating an app which will let you upload some images and then resize them (100x180) and put a 200x200 white background on them.
I've figured on how to resize the images + create the white background but I cannot figure out how to put them together.
Here is the code for resizing and the white background:
public static Bitmap ResizeImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
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(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
private Bitmap DrawFilledRectangle(int x, int y)
{
Bitmap bmp = new Bitmap(x, y);
using (Graphics graph = Graphics.FromImage(bmp))
{
Rectangle ImageSize = new Rectangle(0, 0, x, y);
graph.FillRectangle(Brushes.White, ImageSize);
}
return bmp;
}
Expected result:
Thank you all in advance!

C# Image loses color when saved

I'm working in a little application that will send images to a card printer (Datacard brand), this program should convert the image to only two colors (just like black and white) RGB(217,217,217) and pure white. The problem is that even if in my screen the pictures looks converted, when I save/print the image, it looks black and white.
This method converts the image to black and white so I can later replace only the black color with the RGB 217,217,217
public static Bitmap BitmapTo1Bpp(Bitmap img)
{
int w = img.Width;
int h = img.Height;
Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h),ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
byte[] scan = new byte[(w + 7) / 8];
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
if (x % 8 == 0) scan[x / 8] = 0;
Color c = img.GetPixel(x, y);
if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
}
Marshal.Copy(scan, 0, (IntPtr)((long)data.Scan0 + data.Stride * y), scan.Length);
}
bmp.UnlockBits(data);
return bmp;
}
This method replaces the black color for the new one:
public static Image ImageToRGB217_2(Image image)
{
ColorMatrix colorMatrix = new ColorMatrix(new[]
{
new float[] {0.851f, 0.851f, 0.851f, 1.000f, 0.000f},
new float[] {0.851f, 0.851f, 0.851f, 1.000f, 0.000f},
new float[] {0.851f, 0.851f, 0.851f, 1.000f, 0.000f},
new float[] {0.000f, 0.000f, 0.000f, 0.000f, 0.000f},
new float[] {1.000f, 1.000f, 1.000f, 0.000f, 0.000f}
});
Image img = ApplyColorMatrix(image, colorMatrix);
return img;
}
private static Bitmap ApplyColorMatrix(Image sourceImage, ColorMatrix colorMatrix)
{
Bitmap bmp32BppSource = GetArgbCopy(sourceImage);
Bitmap bmp32BppDest = new Bitmap(bmp32BppSource.Width, bmp32BppSource.Height, PixelFormat.Format32bppArgb);
try
{
using (Graphics graphics = Graphics.FromImage(bmp32BppDest))
{
ImageAttributes bmpAttributes = new ImageAttributes();
bmpAttributes.SetColorMatrix(colorMatrix);
graphics.DrawImage(bmp32BppSource, new Rectangle(0, 0, bmp32BppSource.Width, bmp32BppSource.Height),
0, 0, bmp32BppSource.Width, bmp32BppSource.Height, GraphicsUnit.Pixel, bmpAttributes);
}
bmp32BppSource.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(#"Ocurrió un error al intentar aplicar el filtro UV en una de las imágenes, error:" + ex.Message, "Convertidor", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return bmp32BppDest;
}
private static Bitmap GetArgbCopy(Image sourceImage)
{
Bitmap bmpNew = new Bitmap(sourceImage.Width, sourceImage.Height, PixelFormat.Format32bppArgb);
using (Graphics graphics = Graphics.FromImage(bmpNew))
{
graphics.DrawImage(sourceImage, new Rectangle(0, 0, bmpNew.Width, bmpNew.Height), new Rectangle(0, 0, bmpNew.Width, bmpNew.Height), GraphicsUnit.Pixel);
graphics.Flush();
}
return bmpNew;
}
And here is where I call both:
private void usarFiltroRGB217ToolStripMenuItem_Click(object sender, EventArgs e)
{
pictureBox1.Image = UVImage.ImageToRGB217_2(UVImage.BitmapTo1Bpp((Bitmap)pictureBox1.Image));
pictureBox1.Refresh();
}
This is how the result looks on screen: http://i127.photobucket.com/albums/p128/dawc159951/Preview_zpsxqtzht2a.jpg
But when I save/print, this is what i get:
http://i127.photobucket.com/albums/p128/dawc159951/217_zpsbmuobnrw.png
This is the saving method:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string path = saveFileDialog1.FileName;
Bitmap tmp = (Bitmap)pictureBox1.Image;
tmp.Save(path, ImageFormat.Bmp);
if (File.Exists(path))
Process.Start(path);
}
I would appreciate any help to find out why i'm not able to get result i need.
Thanks in advance.

How to draw a image using C# grapics class

I want to draw a image using using C# graphics class using provided X,Y coordinates and zoom Value. I tried to do this but it is not giving me the correct result.
Stream originalStream = ImageHelper.UrlToImageStream(list1.FirstOrDefault().OriginalImageUrl);
var bmp = new Bitmap(bmp.Width, bmp.Height);
int width = 0;
int height = 0;
var img = new Bitmap(bmp,
(int)(bmp.Size.Width / zoomLevel),
(int)(bmp.Size.Height / zoomLevel));
var g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString(Text, SystemFonts.DefaultFont, Brushes.White, new Rectangle((int)CurrentTextX, (int)CurrentTextY, bmp.Width, bmp.Height));
g.DrawImage(img, new Rectangle((int)CurrentX, (int)CurrentY, bmp.Width, bmp.Height));
var stream = new System.IO.MemoryStream();
img.Save(stream, ImageFormat.Jpeg);
private void mapPaint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Image img = Image.FromFile(#"C:\img.png");
g.DrawImage(img, new Rectangle(10,10,img.Width/zoomLevel, img.Height/zoomLevel);
}
Try it like this also what is the incorrect result you are getting right now?

'System.Runtime.InteropServices.ExternalException'

I keep getting this error of 'System.Runtime.InteropServices.ExternalException' on line 70 "img3.Save(finalImage, System.Drawing.Imaging.ImageFormat.Jpeg);". Originally I had a program that stitched two photos together that worked fine, but I wanted the two images to be the same size (300 pixles by 300 pixles) so I inserted a method:
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
and in my CombineImages method put:
img = resizeImage(img, new Size(300, 300));
but now I am getting an error. Here is my code:
private void cmdCombine_Click(object sender, EventArgs e)
{
//Change the path to location where your images are stored.
DirectoryInfo directory = new DirectoryInfo(#"C:\Users\Elder Zollinger\Desktop\Images");
if (directory != null)
{
FileInfo[] files = directory.GetFiles();
CombineImages(files);
}
}
private void CombineImages(FileInfo[] files)
{
//change the location to store the final image.
string finalImage = #"C:\Users\Elder Zollinger\Desktop\Images\Final.jpg";
List<int> imageHeights = new List<int>();
int nIndex = 0;
int width = 0;
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
img = resizeImage(img, new Size(300, 300));
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
}
imageHeights.Sort();
int height = imageHeights[imageHeights.Count - 1];
Bitmap img3 = new Bitmap(width, height);
Graphics g = Graphics.FromImage(img3);
g.Clear(SystemColors.AppWorkspace);
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
if (nIndex == 0)
{
g.DrawImage(img, new Point(0, 0));
nIndex++;
width = img.Width;
}
else
{
g.DrawImage(img, new Point(width, 0));
width += img.Width;
}
img.Dispose();
}
g.Dispose();
img3.Save(finalImage, System.Drawing.Imaging.ImageFormat.Jpeg);
img3.Dispose();
imageLocation.Image = Image.FromFile(finalImage);
}
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
}
}
It is likely that the image format of the uploaded image cannot be converted directly to Jpeg. One thing we do when resizing is actually draw the image to a new Graphics instance as follows. Note that the first 2 lines attempt to get the pixel and image formats directly from the original image instance - you may have issues with CMYK and images with a transparency layer (GIF/PNG).
var pixelFormat = imgToResize.PixelFormat;
var imageFormat = imgToResize.RawFormat;
Bitmap b = new Bitmap(newWidth.Value, newHeight.Value, pixelFormat);
Graphics g = Graphics.FromImage(b);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawImage(imgToResize, (float)-0.5, (float)-0.5, newWidth.Value + 1, newHeight.Value + 1);
g.Dispose();
b.Save(stream, imageFormat);

Generate transparent PNG c#

I have the function below to generate a sample logo. What I want to do is to return a transparent png or gif instead of a white background.
How can I do that?
private Bitmap CreateLogo(string subdomain)
{
Bitmap objBmpImage = new Bitmap(1, 1);
int intWidth = 0;
int intHeight = 0;
Font objFont = new Font(
"Arial",
13,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Pixel);
Graphics objGraphics = Graphics.FromImage(objBmpImage);
intWidth = (int)objGraphics.MeasureString(subdomain, objFont).Width;
intHeight = (int)objGraphics.MeasureString(subdomain, objFont).Height;
objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));
objGraphics = Graphics.FromImage(objBmpImage);
objGraphics.Clear(Color.White);
objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
objGraphics.DrawString(
subdomain, objFont,
new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);
objGraphics.Flush();
return (objBmpImage);
}
Here is the end result:
context.Response.ContentType = "image/png";
using (MemoryStream memStream = new MemoryStream())
{
CreateLogo(_subdname).Save(memStream, ImageFormat.Png);
memStream.WriteTo(context.Response.OutputStream);
}
In the CreateLogo function:
objGraphics.Clear(Color.White) was changed to objGraphics.Clear(Color.Transparent)
new SolidBrush(Color.FromArgb(102, 102, 102)) changed to new SolidBrush(Color.FromArgb(255, 255, 255))
You can do something like this:
Bitmap bmp = new Bitmap(300, 300);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.Transparent);
g.FillRectangle(Brushes.Red, 100, 100, 100, 100);
g.Flush();
bmp.Save("test.png", System.Drawing.Imaging.ImageFormat.Png);
Take a look at Can you make an alpha transparent PNG with C#?

Categories