如何在图片上绘制文本?

29

我想在图片上绘制文本(以便将带有文本的图片保存下来)。我有一个图像视图,我将位图设置为该图像,我想在图像上绘制文本(由用户输入的文本)。在保存之前,我尝试过以下方法.....

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);
           originalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
           out.flush();
           out.close();

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

这段代码是XML格式的...

<FrameLayout 
     android:id="@+id/framelayout"
     android:layout_marginTop="30dip"
     android:layout_height="fill_parent" 
     android:layout_width="fill_parent">

     <ImageView 
          android:id="@+id/ImageView01"
          android:layout_alignParentTop="true"
          android:layout_height="wrap_content" 
          android:layout_width="wrap_content"/>

     <TextView android:id="@+id/text_view2"
          android:layout_marginTop="20dip"
          android:layout_width="wrap_content" 
          android:text="SampleText"
          android:textSize="12pt"
          android:layout_alignTop="@+id/ImageView01" 
          android:layout_height="wrap_content"/>  

</FrameLayout>

你的问题是什么?你无法绘制文本还是无法保存带有文本的图像? - blessanm86
我的问题是我想在图片上添加文本。 - RajaReddy PolamReddy
7个回答

61

根据Vladislav Skoumal的建议,尝试使用以下方法:

public Bitmap drawTextToBitmap(Context mContext,  int resourceId,  String mText) {
    try {
         Resources resources = mContext.getResources();
         float scale = resources.getDisplayMetrics().density;
         Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId);
         android.graphics.Bitmap.Config bitmapConfig =   bitmap.getConfig();
         // set default bitmap config if none
         if(bitmapConfig == null) {
           bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
         }
         // resource bitmaps are imutable,
         // so we need to convert it to mutable one
         bitmap = bitmap.copy(bitmapConfig, true);

         Canvas canvas = new Canvas(bitmap);
         // new antialised Paint
         Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
         // text color - #3D3D3D
         paint.setColor(Color.rgb(110,110, 110));
         // text size in pixels
         paint.setTextSize((int) (12 * scale));
         // text shadow
         paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);

         // draw text to the Canvas center
         Rect bounds = new Rect();
         paint.getTextBounds(mText, 0, mText.length(), bounds);
         int x = (bitmap.getWidth() - bounds.width())/6;
         int y = (bitmap.getHeight() + bounds.height())/5;

         canvas.drawText(mText, x * scale, y * scale, paint);

         return bitmap;
    } catch (Exception e) {
        // TODO: handle exception

        return null;
    }

}

调用这个方法

Bitmap bmp =drawTextToBitmap(this,R.drawable.aa,"Hello Android");
img.setImageBitmap(bmp);

输出结果

在此输入图片描述


1
@Ruhollahツ 我在4年前发布了这个答案,现在有多个库可用于处理图像。 - Ashish Dwivedi
3
你好,@DwivediJi,你能告诉我这些库的名称吗? - dreampowder
@DwivediJi,这种方法存在一个问题。如果图像尺寸较小,则在图像上绘制的文本会变大。但是,如果图像尺寸较大,则文本会变小。请参考此链接以获取更多详细信息:https://stackoverflow.com/questions/69578026/canvas-drawtext-changes-text-size-for-different-size-images - iCantC

30

更新了SaveImage()方法,以支持文本绘制。

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();
    }
}

如果这对你有用,请告诉我。

Shash


它已经可以工作了,非常感谢...... 经过一些小修改,我更新了答案。 - RajaReddy PolamReddy
2
originalBitmap是什么? - Dr.jacky
1
我对这个解决方案有问题。显示以下错误:位图是不可变的。我该如何解决? - LeandroPortnoy
1
你需要将它变成可变位图。可变位图 mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true); - Ricardo A.

1
  1. 创建一个空的位图
  2. 创建一个新的Canvas对象并将此位图传递给它
  3. 调用view.draw(Canvas)方法,将刚刚创建的canvas对象传递给它。有关详细信息,请参阅该方法的文档。
  4. 使用Bitmap.compress()方法将位图内容写入OutputStream,可以是文件。

伪代码:

Bitmap  bitmap = Bitmap.createBitmap(200,200,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawText();
//necessary arguments and draw whatever you want. thes all are drawn on the bitmap.finally save this bitmap
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); 

我需要在哪里使用它?是在保存函数中还是在onCreate()中? - RajaReddy PolamReddy
这里的“view”指的是您想要绘制的视图。如果您想直接保存为图像,则忽略view.draw(canvas); - Balaji.K
我遇到了强制关闭错误:java.lang.IllegalStateException: Immutable bitmap passed to Canvas constructor。在修改代码后,我的代码变成了:Bitmap bitmap = Bitmap.createBitmap(originalBitmap); Canvas canvas = new Canvas(bitmap); canvas.drawText(my_text, 0, 0, null); FileOutputStream out = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); - RajaReddy PolamReddy

1
您可以扩展视图以创建自定义视图。类似于:
public class PieView extends View { 
    public PieView(Context context) {
        super(context);
        overlayBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.piechart_shade, 
        null);
        overlayWidth  = overlayBitmap.getWidth();
        setLayoutParams(new LayoutParams(overlayWidth, overlayWidth));      
    }

    @Override     
    protected void onDraw(Canvas canvas) {      
        super.onDraw(canvas);
    }
}

在ondraw方法中,您可以使用canvas.drawBitmap和canvas.drawText绘制位图和文本。
这样做的好处是,您不需要使用framelayout,因为一切都在一个自定义视图中。
您可以将此包含在xml文件中,如下所示:
<com.raj.PieView android:id="@+id/framelayout" android:layout_marginTop="30dip"      
    android:layout_height="fill_parent" android:layout_width="fill_parent"/>

我有更多的相对布局和按钮的XML代码,如何将其添加到我的代码中? - RajaReddy PolamReddy

0

用 TextView 替换它。在 XML 中放置一个 TextView,并像按钮一样进行充气。 - Pavankumar Vijapur
将以下代码放入您的main.xml中:<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/dynamic_text"
</TextView>,然后将上述代码复制并粘贴到您的oncreate中。将layout1替换为main。在string s.xml中添加一个值给dynamic_text。
- Pavankumar Vijapur
在添加了以下代码后,出现了强制关闭错误:fl =(FrameLayout)findViewById(R.id.framelayout);最终LayoutInflater inflater =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);tv =(TextView)inflater.inflate(R.id.text_view2,null);fl.addView(tv);请查看我的编辑,我添加了一些代码部分。 - RajaReddy PolamReddy

0
如果您正在使用Glide获取图像,则我修改了@Dwivedi的答案(使用kotlin)如下:
Glide.with(this)
        .asBitmap()
        .load("https://images.pexels.com/photos/1387577/pexels-photo-1387577.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260")
        .into(object : CustomTarget<Bitmap>() {
            override fun onLoadCleared(placeholder: Drawable?) {}

            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                val bm = resource.copy(Bitmap.Config.ARGB_8888, true)
                val tf = Typeface.create("Helvetica", Typeface.BOLD)

                val paint = Paint()
                paint.style = Paint.Style.FILL
                paint.color = Color.WHITE
                paint.typeface = tf
                paint.textAlign = Paint.Align.LEFT
                paint.textSize = dip(25).toFloat()

                val textRect = Rect()
                paint.getTextBounds("HELLO WORLD", 0, "HELLO WORLD".length, textRect)

                val canvas = Canvas(bm)

                //If the text is bigger than the canvas , reduce the font size
                if (textRect.width() >= canvas.width - 4)
                //the padding on either sides is considered as 4, so as to appropriately fit in the text
                    paint.textSize = dip(12).toFloat()

                //Calculate the positions
                val xPos = canvas.width.toFloat()/2 + -2

                //"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center.
                val yPos = (canvas.height / 2 - (paint.descent() + paint.ascent()) / 2) + 0

                canvas.drawText("HELLO WORLD", xPos, yPos, paint)

                binding.imageDrawable.setImageBitmap(bm)
            }

        })

0

我解决了这个问题(不可变文件),但是文件中没有写入任何内容...请看我的代码: public static File writeOnImage(File file) throws IOException {

    Bitmap originalBitmap = BitmapFactory.decodeFile(file.getPath());
    originalBitmap = convertToMutable(originalBitmap);
    FileOutputStream out = new FileOutputStream(file);

    try {
        Canvas canvas = new Canvas(originalBitmap);

        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStrokeWidth(12);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
        canvas.drawBitmap(originalBitmap, 0, 0, paint);
        canvas.drawText("Testing...", 10, 10, paint);

        originalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

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

    return file;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接