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#?
Related
I am using Telerik RadBarcode in my Asp.Net web application. See my code to generate the RadBarcode programmatically.
RadBarcode barcode = new RadBarcode();
barcode.Type = BarcodeType.Code128;
barcode.ID = "RadBarcode1";
rcode.Text = "656146114";
barcode.ShowText = true;
barcode.OutputType = BarcodeOutputType.SVG_VML;
Bitmap bitmap1 = new Bitmap(barcode.GetImage());
bitmap1.Save("D:\\" + "\\bmap.jpg");
While saving the barcode as an image the text under the barcode is missing in my case.
We can place a label below the barcode image to show the text and create one new bitmap image which contains the text and barcode data. Refer to the example below;
RadBarcode barcodeRB = new RadBarcode();
barcodeRB.Type = BarcodeType.Code128;
barcodeRB.Text ="123456789";
barcodeRB.ShowText = true;
barcodeRB.OutputType = BarcodeOutputType.SVG_VML;
Bitmap bitmap1 = new Bitmap(barcodeRB.GetImage());
System.Drawing.Image image = barcodeRB.GetImage();
Bitmap barCanvas = new Bitmap(435, 205);
barCanvas.SetResolution(90, 90);
using (Graphics gfx = Graphics.FromImage(barCanvas))
using (SolidBrush brush = new SolidBrush(Color.FromArgb(255, 255, 255)))
{
gfx.FillRectangle(brush, 0, 0, 435, 205);
}
using (Graphics gr = Graphics.FromImage(barCanvas))
{
RectangleF rectf = new RectangleF(150, 170, 300, 50);
gr.DrawImage(image, 20, 20, 400, 150);
gr.DrawString(studentTest.BarcodeString, new Font("GenericSansSerif", 26), Brushes.Black, rectf);
}
barCanvas.Save("D:\" + "\bmap.jpg");
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.
This question already has answers here:
Free c# QR-Code generator [closed]
(4 answers)
Closed 7 years ago.
After using this lines of code bellow
private void button1_Click(object sender, EventArgs e)
{
string barcode = textBox1.Text;
Bitmap bitmap = new Bitmap(barcode.Length * 40, 150);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
Font oFont = new System.Drawing.Font("IDAutomationHC39M", 20);
PointF point = new PointF(2f, 2f);
SolidBrush white = new SolidBrush(Color.White);
SolidBrush black = new SolidBrush(Color.Black);
graphics.FillRectangle(white,0,0,bitmap.Width,bitmap.Height);
graphics.DrawString("*" + barcode + "*", oFont, black, point);
}
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms,ImageFormat.Png);
pictureBox1.Image = bitmap;
pictureBox1.Height = bitmap.Height;
pictureBox1.Width = bitmap.Width;
}
}
i was able to generate this output image barcode
i want to generate a bar code that output like the image bellow how can i achieve this
You can do it like this
private System.Drawing.Image GenerateQRCode(string content, int size)
{
QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.H);
QrCode qrCode;
encoder.TryEncode(content, out qrCode);
GraphicsRenderer gRenderer = new GraphicsRenderer(new FixedModuleSize(4, QuietZoneModules.Two), System.Drawing.Brushes.Black, System.Drawing.Brushes.White);
//Graphics g = gRenderer.Draw(qrCode.Matrix);
MemoryStream ms = new MemoryStream();
gRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Bmp, ms);
var imageTemp = new Bitmap(ms);
var image = new Bitmap(imageTemp, new System.Drawing.Size(new System.Drawing.Point(size, size)));
//image.Save("file.bmp", ImageFormat.Bmp);
return (System.Drawing.Image)image;
}
Implementaion
string barcode = textBox1.Text;
codeImage = GenerateQRCode(barcode, 120);
// you can make a smaller image as per your need
rect = new System.Drawing.Rectangle(1080, 530, codeImage.Width, codeImage.Height);
using (Graphics g = Graphics.FromImage(picEdit))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawImage(codeImage, rect);
}
Do not forget to add
using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
from GitHub: QrCode.Net
I am creating a PNG picture, using the Bitmap object, using Drawing.Graphics . I create a Bitmap, insert a background image and draw some strings.
Now, when I save the image on the disk, the files does not have my strings!
I am doing this in ASP.NET MVC, where this is my controllers signature:
[AcceptVerbs(HttpVerbs.Get)]
public string GetNewsletterPicture(string headline, string tagline)
When I don't save the image on the disk and instead returns a FileStreamResult from a MemoryStream, the image looks perfectly.
So there is some problem that when I save the image to the disk, the strings are "forgotten" somehow.
Any ideas?
My code:
ColorConverter converter = new ColorConverter();
Color textColor = (Color)converter.ConvertFromString("#FF58595B");
int width = 598;
int height = 77;
int offSet = 40;
int shadowOffset = 1;
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
Image backgroundImg = new Bitmap(Server.MapPath("~/Static/Images/bgimg.png"));
g.DrawImage(backgroundImg,0,0);
StringFormat sf= new StringFormat();
sf.Alignment = StringAlignment.Center;
var rectangleTop = new RectangleF(0, 0, width, height);
var rectangleTopShadowHack = new RectangleF(shadowOffset, shadowOffset, width + shadowOffset, height + shadowOffset);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// only show headline and center it
if (!string.IsNullOrEmpty(tagline))
{
var rectangleBottomShadowHack = new RectangleF(shadowOffset, offSet + shadowOffset, width + shadowOffset, height - offSet + shadowOffset);
var rectangleBottom = new RectangleF(0, offSet, width, height - offSet);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(Color.White), rectangleBottomShadowHack, sf);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(textColor), rectangleBottom, sf);
}
else
{
sf.LineAlignment = StringAlignment.Center;
}
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(Color.White), rectangleTopShadowHack, sf);
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(textColor), rectangleTop, sf);
g.Save();
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png);
return fileName;
If in doubt, it is the g.DrawString which is not being saved on the picture.
NEW atttempt (still not working):
[AcceptVerbs(HttpVerbs.Get)]
public string GetNewsletterPicture(string headline, string tagline)
{
ColorConverter converter = new ColorConverter();
Color textColor = (Color)converter.ConvertFromString("#FF58595B");
int width = 598;
int height = 77;
int offSet = 40;
int shadowOffset = 1;
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.LightGray);
Image backgroundImg = new Bitmap(Server.MapPath("~/Static/Images/bgimg.png"));
g.DrawImage(backgroundImg,0,0);
StringFormat sf= new StringFormat();
sf.Alignment = StringAlignment.Center;
var rectangleTop = new RectangleF(0, 0, width, height);
var rectangleTopShadowHack = new RectangleF(shadowOffset, shadowOffset, width + shadowOffset, height + shadowOffset);
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// only show headline and center it
if (!string.IsNullOrEmpty(tagline))
{
var rectangleBottomShadowHack = new RectangleF(shadowOffset, offSet + shadowOffset, width + shadowOffset, height - offSet + shadowOffset);
var rectangleBottom = new RectangleF(0, offSet, width, height - offSet);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(Color.White), rectangleBottomShadowHack, sf);
g.DrawString(tagline, new Font("Verdana", 18), new SolidBrush(textColor), rectangleBottom, sf);
}
else
{
sf.LineAlignment = StringAlignment.Center;
}
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(Color.White), rectangleTopShadowHack, sf);
g.DrawString(headline, GetFont("Sentinel-Bold", 28, FontStyle.Bold), new SolidBrush(textColor), rectangleTop, sf);
g.Flush(FlushIntention.Sync);
}
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png);
return fileName;
//MemoryStream stm = new MemoryStream();
//bmp.Save(stm,System.Drawing.Imaging.ImageFormat.Png);
//stm.Position = 0;
//return new FileStreamResult(stm, "image/png");
}
I can't tell for sure, but it looks like you might be confusing g.Save() with g.Flush().
You need to call g.Flush(FlushIntention.Sync) instead of g.Save(). You should probably also call bmp.Save() outside of the using block:
var bmp = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bmp))
{
//...
g.Flush(FlushIntention.Sync);
}
var fileName = Guid.NewGuid().ToString() + ".png";
var path = Server.MapPath("~/Static/Previews/" + fileName);
bmp.Save(path, ImageFormat.Png)
Save() is used to save the current graphics state so that you can modify it and then restore it later.:
GraphicsState oldState = g.Save();
// Make some changes to the graphics state...
g.Restore(oldState);
Flush() on the other hand, is used to force the graphics object to complete any pending operations. By passing FlushIntention.Sync as a parameter, Flush() won't return until the flushing is complete.
This is my code to create barcode image:
class Program
{
static void Main(string[] args)
{
CreateBarcode("The quick brown fox jumps over the lazy dog".ToUpper());
}
private static void CreateBarcode(string code)
{
var myBitmap = new Bitmap(500, 50);
var g = Graphics.FromImage(myBitmap);
var jgpEncoder = GetEncoder(ImageFormat.Jpeg);
g.Clear(Color.White);
var strFormat = new StringFormat { Alignment = StringAlignment.Center };
g.DrawString(code, new Font("Free 3 of 9", 50), Brushes.Black, new RectangleF(0, 0, 500, 50), strFormat);
var myEncoder = Encoder.Quality;
var myEncoderParameters = new EncoderParameters(1);
var myEncoderParameter = new EncoderParameter(myEncoder, 100L);
myEncoderParameters.Param[0] = myEncoderParameter;
//MemoryStream memoryStrem = new
myBitmap.Save(#"d:\Barcode.jpg", jgpEncoder, myEncoderParameters);
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
var codecs = ImageCodecInfo.GetImageDecoders();
foreach (var codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
}
This works fine however, this line: g.DrawString(code, new Font("Free 3 of 9", 50), Brushes.Black, new RectangleF(0, 0, 500, 50), strFormat);
as you can see the width here is 500. Now if I specify a big paragraph of text I fear that 500 would not be enough. Is there any way to make this width dynamic based on content?
Its too old to answer, Still am posting as it may help some one. We can create graphics object with a dummy bitmap and try find the length of font, after than re-initialize the bitmap as well as graphics object.
var myBitmap = new Bitmap(1, 1);
Font threeOfNine = new Font("Free 3 of 9", 60, FontStyle.Regular, GraphicsUnit.Point);
var g = Graphics.FromImage(myBitmap);
SizeF dataSize = g.MeasureString(code, threeOfNine);
myBitmap = new Bitmap(myBitmap, dataSize.ToSize());
g = Graphics.FromImage(myBitmap);