Adding text to a bitmap with canvas - c#

I have some code that adds text to a bitmap. This works well unless the text is wider than the original image.
How do I go about making the image wide enough for my text to display correctly?
Here is my code:
private BitmapDescriptor GetCustomBitmapDescriptor(string text)
{
Bitmap baseBitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.Icon);
Bitmap bitmap = baseBitmap.Copy(Bitmap.Config.Argb8888, true);
Paint paint = new Paint(PaintFlags.AntiAlias);
Rect bounds = new Rect();
paint.GetTextBounds(text, 0, text.Length, bounds);
float bitmapMiddle = bitmap.Width / 2.0f;
Canvas canvas = new Canvas(bitmap);
canvas.DrawText(text, bitmapMiddle - (bounds.Right / 2.0f), bitmap.Height, paint);
BitmapDescriptor icon = BitmapDescriptorFactory.FromBitmap(bitmap);
return (icon);
}
Thanks in advance.

Just color code and it is working
private Bitmap GetCustomBitmapDescriptor(String text)
{
Bitmap baseBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launche);
Bitmap bitmap = baseBitmap.copy(Bitmap.Config.ARGB_8888, true);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
float bitmapMiddle = bitmap.getWidth() / 2.0f;
Canvas canvas = new Canvas(bitmap);
paint.setColor(Color.RED);
canvas.drawText(text, bitmapMiddle - (bounds.right / 2.0f), bitmap.getHeight(), paint);
return bitmap;
}

Related

how to have my rectangle always on the middle of the image without knowing the size of the incomming image

Trying to add a watermark image to a png image, i´ve been able to do it, but i want to take out the hardCoded size regulation for the rectangle of the waterMark, and make it always stay in the center of the image. How can i achieve this.
public Form1()
{
InitializeComponent();
picBox.Parent = this;
picBox.Dock = DockStyle.Fill;
picBox.SizeMode = PictureBoxSizeMode.Zoom;
Bitmap Jpg = new Bitmap(#"C:\Users\tferreira\Desktop\213123.PNG");
using (Bitmap Bmp = new Bitmap(#"C:\Users\tferreira\Desktop\logo.png"))
{
using (Bitmap WatermarkBmp = new Bitmap(Bmp, Bmp.Width / 1, Bmp.Height / 1))
{
picBox.Image = WatermarkImage(Jpg, WatermarkBmp, new Point(400, 100), 0.40F);
}
}
}
public Bitmap WatermarkImage(Bitmap ImageToWatermark, Bitmap Watermark, Point WatermarkPosition, float Opacity)
{
using (Graphics G = Graphics.FromImage(ImageToWatermark))
{
using (ImageAttributes IA = new ImageAttributes())
{
ColorMatrix CM = new ColorMatrix();
CM.Matrix33 = Opacity;
IA.SetColorMatrix(CM);
G.DrawImage(Watermark, new Rectangle(WatermarkPosition, Watermark.Size), 0, 0, Watermark.Width, Watermark.Height, GraphicsUnit.Pixel, IA);
}
}
return ImageToWatermark;
}
Right now the images are hardCoded but that will be taken out. If anyone can help me make this watermark allways stay centered i thank you.
I fixed this problem with this nice peace of code.
System.Drawing.Image img = System.Drawing.Image.FromFile(JpgFilePath);
Bitmap jpg = new Bitmap(img);
filePath = JpgFilePath;
int Width = jpg.Width;
int Height = jpg.Height;
jpg.SetResolution(300, 300);
WaterMarked = WatermarkImage(jpg, WaterMarkBit, new Point((Width - WaterMarkBit.Width) / 2, (Height - WaterMarkBit.Height) / 2), 0.4F);
WaterMarked.Save(filePath.Replace(".jpg", "") + ".tif", ImageFormat.Tiff);
filesJpgForTif.Add(JpgFilePath.Replace("jpg", "tif"));
Using the the sizes of the image and sizes of the watermark and divide it by 2 it makes the image always stay centered.

Unable to get correct Size of DrawnText using TextRenderer

Im drawing Text using the following code onto a Bitmap
GraphicsPath pth = new GraphicsPath();
var style = (int)myfont.Style;
pth.AddString(tcaption.Text, myfont.FontFamily, style, myfont.Size, point, StringFormat.GenericTypographic);
p = new Pen(new SolidBrush(bc), 2f);
mygraphics.DrawPath(p, pth);
I'm using the TextRenderer to measure the size of the string..
int Width = TextRenderer.MeasureText(tcaption.Text, myfont).Width;
But this does not produce the correct size of the drawn string; there is around 20-30% difference from the actual size of the drawn string?
What im i doing wrong? Please advice.
UPDATE:
I want to draw a Text and an Image onto a Bitmap,so inorder to accommodate both i'm creating an Bitmap like this
intWidth = TextRenderer.MeasureText(tcaption.Text, cfont).Width + image.Width;
intHeight = TextRenderer.MeasureText(tcaption.Text, cfont).Height +image.Height;
tempimage= new Bitmap(intWidth, intHeight);
Then i create Graphics object from the Bitmap like this
using (Graphics newg = Graphics.FromImage(tempimage))
#Hans Passant
I have also tried the Graphics.MeasureString as an alternative to TextRenderer
Now i set the position of the text and image-I need to draw the image at the top left corner .. so
imageposy = 0;
imageposx = 10;
textposy = image.Height;
textposx = 0;
Then i draw the text like this
po=new Point(textposx, textposy);
newg.SmoothingMode = SmoothingMode.AntiAlias;
GraphicsPath pth = new GraphicsPath();
var style = (int)myfont.Style;
pth.AddString(tcaption.Text, myfont.FontFamily, style, myfont.Size, po,
StringFormat.GenericTypographic);
newg.FillPath(new SolidBrush(fc), pth);
Now i draw the image like this
Rectangle nrect = new Rectangle(imageposx, imageposy, image.Width,
image.Height);
objGraphics = Graphics.FromImage(tempimage);
objGraphics.DrawImage(image, nrect);
As you have seen i need to add the offset 10 to imageposition x coordinate to correct the measurement issue.
Hope my update throws more light into the question... what im i doing wrong?
Please advice..
instead of using TextRenderer use GraphicsPath:
var path = new GraphicsPath();
path.AddString(text, font.FontFamily, (int)font.Style, size, new Point(0, 0), StringFormat.GenericTypographic);
var area = Rectangle.Round(path.GetBounds());
Here is sample code that generates image with size of text:
private Image DrawText(String text, Font font, int size, Color textColor, Color backColor)
{
var path = new GraphicsPath();
path.AddString(text, font.FontFamily, (int)font.Style, size, new Point(0, 0), StringFormat.GenericTypographic);
var area = Rectangle.Round(path.GetBounds());
Rectangle br = Rectangle.Round(path.GetBounds());
var img = new Bitmap(br.Width, br.Height);
var drawing = Graphics.FromImage(img);
drawing.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
drawing.SmoothingMode = SmoothingMode.HighSpeed;
drawing.Clear(backColor);
drawing.TranslateTransform((img.Width - br.Width) / 2 - br.X, (img.Height - br.Height) / 2 - br.Y);
drawing.FillPath(Brushes.Black, path);
Brush textBrush = new SolidBrush(textColor);
drawing.Save();
textBrush.Dispose();
drawing.Dispose();
return img;
}
Here are sample results:

Watermark not drawing in image

I had an error come up:
A Graphics Object cannot be Created from an Image that has an Indexed Pixel Format
So I implemented this code into my method: Solution for "A Graphics Object cannot be Created from an Image that has an Indexed Pixel Format"
But now my watermark doesnt want to draw on my image.
Please can anyone assist.
Code:
private Image AddWaterMark(Image original)
{
Image waterMark = Image.FromFile(ConfigurationManager.AppSettings["GalleryFolder"] + #"\watermark.png");
Bitmap bm = (Bitmap)original;
Size waterMarkResize = ResizeFit(new Size(original.Width, original.Height));
using (Image watermarkImage = new Bitmap(waterMark, waterMarkResize))
using (Graphics imageGraphics = Graphics.FromImage(new Bitmap(bm.Width, bm.Height)))
{
imageGraphics.DrawImage(bm, new Rectangle(0, 0, bm.Width, bm.Height), 0, 0, bm.Width, bm.Height, GraphicsUnit.Pixel);
using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))
{
int x = (original.Width / 2 - watermarkImage.Width / 2);
int y = (original.Height / 2 - watermarkImage.Height / 2);
watermarkBrush.TranslateTransform(x, y);
imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width + 1, watermarkImage.Height)));
}
}
return bm;
}
You're creating a new Bitmap to pass to Graphics.FromImage then returning the uneditted original Bitmap. Create the new Bitmap independently, pass it to FromImage then return the new Bitmap.
var edit = new Bitmap(bm.Width, bm.Height);
// ...
using (Graphics imagesGraphics = Graphics.FromImage(edit))
{
// draw original
// draw watermark
}
return edit;

Use croppic to rotate images

I am using croppic to crop images. Is there any possibility to extend its functionality to rotate the image, before sending it to crop. Something like this
var angle = 0;
$('#button').on('click', function() {
angle += 90;
$("#image").rotate(angle);
});
Here is the demo
I can manage to to rotate the image, but the cropped image is not in rotated position. Any idea?
Update:
Now the image is getting rotated. I have managed to keep rotated image by the same handler that uses crop method. But the cropped image in rotated position occurs only when the rotated image is in 180 rotation. When its in the 90/270, the image, obviously don't fit in the bounding box (if you have seen croppic) and I get a MemoryOutOfBound exception.
Here is the code:
public static Bitmap RotateImage(Bitmap bmpSrc, float theta)
{
Matrix mRotate = new Matrix();
mRotate.Translate(bmpSrc.Width / -2, bmpSrc.Height / -2, MatrixOrder.Append);
mRotate.RotateAt(theta, new System.Drawing.Point(0, 0), MatrixOrder.Append);
using (GraphicsPath gp = new GraphicsPath())
{ // transform image points by rotation matrix
gp.AddPolygon(new System.Drawing.Point[] { new System.Drawing.Point(0, 0), new System.Drawing.Point(bmpSrc.Width, 0), new System.Drawing.Point(0, bmpSrc.Height) });
gp.Transform(mRotate);
System.Drawing.PointF[] pts = gp.PathPoints;
// create destination bitmap sized to contain rotated source image
Rectangle bbox = boundingBox(bmpSrc, mRotate);
Bitmap bmpDest = new Bitmap(bbox.Width, bbox.Height);
using (Graphics gDest = Graphics.FromImage(bmpDest))
{ // draw source into dest
Matrix mDest = new Matrix();
mDest.Translate(bmpDest.Width / 2, bmpDest.Height / 2, MatrixOrder.Append);
gDest.Transform = mDest;
gDest.DrawImage(bmpSrc, pts);
return bmpDest;
}
}
}
private static Rectangle boundingBox(Image img, Matrix matrix)
{
GraphicsUnit gu = new GraphicsUnit();
Rectangle rImg = Rectangle.Round(img.GetBounds(ref gu));
// Transform the four points of the image, to get the resized bounding box.
System.Drawing.Point topLeft = new System.Drawing.Point(rImg.Left, rImg.Top);
System.Drawing.Point topRight = new System.Drawing.Point(rImg.Right, rImg.Top);
System.Drawing.Point bottomRight = new System.Drawing.Point(rImg.Right, rImg.Bottom);
System.Drawing.Point bottomLeft = new System.Drawing.Point(rImg.Left, rImg.Bottom);
System.Drawing.Point[] points = new System.Drawing.Point[] { topLeft, topRight, bottomRight, bottomLeft };
GraphicsPath gp = new GraphicsPath(points,new byte[] { (byte)PathPointType.Start,
(byte)PathPointType.Line, (byte)PathPointType.Line,
(byte)PathPointType.Line });
gp.Transform(matrix);
return Rectangle.Round(gp.GetBounds());
}
I think main issue is in the bounding box.
using (Bitmap rotate = new Bitmap(RotateImage(bmp, rotateAngle)))
{
using (Bitmap cloneRotate = (Bitmap)rotate.Clone()) //getting error here
{
//some stuffs
cloneRotate.save(mycroppedimageurl);
}
}

C#: Draw one Bitmap onto Another, with Transparency

I have two Bitmaps, named largeBmp and smallBmp. I want to draw smallBmp onto largeBmp, then draw the result onto the screen. SmallBmp's white pixels should be transparent. Here is the code I'm using:
public Bitmap Superimpose(Bitmap largeBmp, Bitmap smallBmp) {
Graphics g = Graphics.FromImage(largeBmp);
g.CompositingMode = CompositingMode.SourceCopy;
smallBmp.MakeTransparent();
int margin = 5;
int x = largeBmp.Width - smallBmp.Width - margin;
int y = largeBmp.Height - smallBmp.Height - margin;
g.DrawImage(smallBmp, new Point(x, y));
return largeBmp;
}
The problem is that the result winds up transparent wherever smallBmp was transparent! I just want to see through to largeBmp, not to what's behind it.
CompositingMode.SourceCopy is the problem here. You want CompositingMode.SourceOver to get alpha blending.
Specify the transparency color of your small bitmap. e.g.
Bitmap largeImage = new Bitmap();
Bitmap smallImage = new Bitmap();
--> smallImage.MakeTransparent(Color.White);
Graphics g = Graphics.FromImage(largeImage);
g.DrawImage(smallImage, new Point(10,10);
Winform copy image on top of another
private void timerFFTp_Tick(object sender, EventArgs e)
{
if (drawBitmap)
{
Bitmap bitmap = new Bitmap(_fftControl.Width, _fftControl.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
_fftControl.DrawToBitmap(bitmap, new Rectangle(0, 0, _fftControl.Width, _fftControl.Height));
if (!fDraw)
{
bitmap.MakeTransparent();
Bitmap fftFormBitmap = new Bitmap(_fftForm.BackgroundImage);
Graphics g = Graphics.FromImage(fftFormBitmap);
g.DrawImage(bitmap, 0, 0);
_fftForm.BackgroundImage = fftFormBitmap;
}
else
{
fDraw = false;
_fftForm.Width = bitmap.Width + 16;
_fftForm.Height = bitmap.Height + 48;
_fftForm.BackgroundImage = bitmap;
}
}
}

Categories

Resources