How to Draw Text on Image

How to draw text On image?

Updated SaveImage() method, to support text drawing.

void saveImage() {
File myDir=new File("/sdcard/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);

// NEWLY ADDED CODE STARTS HERE [
Canvas canvas = new Canvas(originalBitmap);

Paint paint = new Paint();
paint.setColor(Color.WHITE); // Text Color
paint.setTextSize(12); // Text Size
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); // Text Overlapping Pattern
// some more settings...

canvas.drawBitmap(originalBitmap, 0, 0, paint);
canvas.drawText("Testing...", 10, 10, paint);
// NEWLY ADDED CODE ENDS HERE ]

originalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Let me know if this works for you.

Shash

How to draw text on image and show it in a grid?

I have used one function which converts my image + text in a bitmap. Then I am able to display that bitmap image easily in grid view.
Here is my output with gridview.

Sample Image

//create bitmap from view and returns it
public static Bitmap getBitmapFromView(View view) {
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null) {
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
} else {
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
}
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}

Here view is my RelativeLayout which contains image-view and edit-text. Hope I have understood your question well and you got hint from this.

How to draw text on an image and save it using UWP (for Windows 10)

I want to draw text on a template image in UWP (for Windows 10), and then be able to save the image (so the user could print or share it).

According to your code snippet, you are trying to use RenderTargetBitmap which can meet your requirements. This class can render the Image with the TextBlock together into one image. Your code snippet just lack of saving. You can save the rendered image as follows:

private async void btnSaveImage_Click(object sender, RoutedEventArgs e)
{
RenderTargetBitmap bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(MyCreatedImage);

var pixelBuffer = await bitmap.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();
var displayInformation = DisplayInformation.GetForCurrentView();
StorageFolder pictureFolder = KnownFolders.SavedPictures;
var file = await pictureFolder.CreateFileAsync("test2.jpg", CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)bitmap.PixelWidth,
(uint)bitmap.PixelHeight,
displayInformation.RawDpiX,
displayInformation.RawDpiY,
pixels);
await encoder.FlushAsync();
}
}

You may also try to use Win2D which may be recommended. You can draw images, draw text and draw shapes as you want. It provides the CanvasBitmap.SaveAsync method for saving the result. For example, the following demo showed how to draw the text on the image and save it to the picture folder.

Uri imageuri = new Uri("ms-appx:///Assets/HelloMyNameIs.jpg");
StorageFile inputFile = await StorageFile.GetFileFromApplicationUriAsync(imageuri);
BitmapDecoder imagedecoder;
using (var imagestream = await inputFile.OpenAsync(FileAccessMode.Read))
{
imagedecoder =await BitmapDecoder.CreateAsync(imagestream);
}
CanvasDevice device = CanvasDevice.GetSharedDevice();
CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, imagedecoder.PixelWidth, imagedecoder.PixelHeight, 96);
using (var ds = renderTarget.CreateDrawingSession())
{
ds.Clear(Colors.White);
CanvasBitmap image = await CanvasBitmap.LoadAsync(device, inputFile.Path, 96);
ds.DrawImage(image);
ds.DrawText(lblName.Text, new System.Numerics.Vector2(150, 150), Colors.Black);
}
string filename = "test1.png";
StorageFolder pictureFolder = KnownFolders.SavedPictures;
var file = await pictureFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
}

If you want personality text drawing on the image you may consider using InkCanvas to DrawInk. Details you may reference this thread.

Draw text on image

Try to draw directly on the TBitmap of the timage instead of the Canvas of the TImage.

You need also to create a bitmap of your image before you try to access it:

AImage.Bitmap := TBitmap.Create(Round(AImage.Width), Round(AImage.Height));

So the correct code will be something like this:

procedure TfMain.TextToImage(const AText: string; const AImage: TImage);
begin
if NOT Assigned(AImage) then Exit;
AImage.Bitmap := TBitmap.Create(Round(AImage.Width), Round(AImage.Height));
AImage.Bitmap.Canvas.BeginScene;
try
//....
// Use AImage.Bitmap.Canvas as needed
AImage.Bitmap.Canvas.FillText( AImage.AbsoluteRect,
AText,
False,
1,
[],
TTextAlign.Center,
TTextAlign.Center);
finally
AImage.Bitmap.Canvas.EndScene;
end;
end;

From the TImage.Paint event code you will see:

procedure TImage.Paint;
var
R: TRectF;
begin
if (csDesigning in ComponentState) and not Locked and not FInPaintTo then
begin
R := LocalRect;
InflateRect(R, -0.5, -0.5);
Canvas.DrawDashRect(R, 0, 0, AllCorners, AbsoluteOpacity, $A0909090);
end;

UpdateCurrentBitmap;
if FCurrentBitmap <> nil then
DrawBitmap(Canvas, LocalRect, FCurrentBitmap, AbsoluteOpacity);
end;

So no matter what you will paint on the canvas, on the next repaint it will draw again the full bitmap erasing what you already done.

If you don't want to touch the bitmap than you need to override the OnPaint event of theTImage and call function TextToImage(const AText: string; const AImage: TImage);

How to draw text onto an image in Android

Achieved by doing:

public static Bitmap viewToBitmap(Activity activity, Bitmap bitmap, String mapURL, String latLong, String dateTime) {

try {

AsyncTask asyncTask = new BackgroundUtils.setImageFromUrl().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, mapURL);
Bitmap googleBitmap = (Bitmap) asyncTask.get();

Bitmap.Config bitmapConfig = bitmap.getConfig();

if (bitmapConfig == null) {
bitmapConfig = Bitmap.Config.ARGB_8888;
}

Bitmap bmp = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bmp);
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

ViewGroup root = (ViewGroup) activity.findViewById(R.id.relativeLayout);
View layout = inflater.inflate(R.layout.screenshot_content, root, false);
ImageView cameraView = (ImageView) layout.findViewById(R.id.cameraView);
ImageView mapView = (ImageView) layout.findViewById(R.id.mapView);
TextView latLongView = (TextView) layout.findViewById(R.id.latLongView);
TextView dateTimeView = (TextView) layout.findViewById(R.id.dateTimeView);

cameraView.setImageBitmap(bitmap);
mapView.setImageBitmap(googleBitmap);
latLongView.setText(latLong);
dateTimeView.setText(dateTime);

layout.setDrawingCacheEnabled(true);
layout.measure(View.MeasureSpec.makeMeasureSpec(canvas.getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(canvas.getHeight(), View.MeasureSpec.EXACTLY));
layout.layout(0, 0, layout.getMeasuredWidth(), layout.getMeasuredHeight());
layout.draw(canvas);

return bmp;
} catch (Exception e) {
e.printStackTrace();
}

return null;

}

Outline text on image in Python

I don't know since what version, but about a year ago Pillow added text stroking. You probably need to update it if you haven't do so lately. Example usage with stroke_width of 2:

from PIL import Image, ImageDraw, ImageFont

caption = 'I need to update my Pillow'
img = Image.open('./example-img.jpg')
d = ImageDraw.Draw(img)
font = ImageFont.truetype('impact.ttf', size=50)
d.text((10, 400), caption, fill='white', font=font,
stroke_width=2, stroke_fill='black')
img.save('example-output.jpg')

Pillow draw text on image - clear between iterations Python

Take a fresh copy of the original each time before you write on it, like this:

from PIL import Image, ImageDraw

# Open the image
im = Image.open('image.png')

# Make a list of the annotation texts
words = ['the', 'cat', 'sat', 'on', 'the', 'mat']

# Iterate over all annotations
for word in words:
# Take a clean copy of original image - the following line is the actual answer
clear = im.copy()

# Draw the text on the clean copy and save
draw = ImageDraw.Draw(clear)
draw.text((10,10), word)
clear.save(word + '.png')

Draw text to image change bug

If you don't need Verdana (which isn't a monospaced font), you should be able to fix this by slightly altering your call to DrawText like so:

DrawText(table, new Font(FontFamily.GenericMonospace, 20), Color.Black, Color.White);

I'm not actually super familiar with working with fonts, so using FontFamily.GenericMonospace is sort of my best guess. You should be able to use others though. Wikipedia has a list of them.



Related Topics



Leave a reply



Submit