0
1

More than 1 year has passed since last update.

Androidで写真にテキストを合成する

Posted at

Androidで写真にテキストを合成する

(注意)
Bitmapに変換して画像を合成すると元の写真が持つExif情報は失われます。
写真の向きなどを表すExifInterface.TAG_ORIENTATIONなど必要な情報は引き継ぐように実装した方がいいかもしれません。

1.合成したい元の写真をBitmapに変換して写真と同じ大きさのCanvasに貼り付けます。

以下のsourcePathに元写真のパスが入ってます。

val baseBitmap = BitmapFactory.decodeFile(sourcePath)
val width = baseBitmap.width
val height = baseBitmap.height
val newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(baseBitmap)
canvas.drawBitmap(baseBitmap, 0f, 0f, null)
2.テキストを描くためのPaintオブジェクトを作成します。
val dataText = "おはようございます。こんにちは。こんばんは。"
val paintText = Paint()
// 色を指定する
paintText.color = Color.Red

// フォントサイズを指定する
// ここでは最初は大きめのフォントを指定しておいて、
// テキストの幅がCanvasの幅を超えないように
// フォントサイズを調整しています。 
paintText.textSize = 300f
while (paintText.measureText(dateText) > width) {
   paintText.textSize -= 2
}
3.Canvasに文字列を描きます
// 日付文字列を描く
canvas.drawText(dateText, 0f, 0f, paintText)

画面の右下などに配置したい場合はPaintオブジェクトのfontMetricsから
テキストの高さを、measureTextメソッドから幅を取得し良い感じに配置されるよう調整しましょう。

4.JPEGファイルに出力する

以下のdistFileは出力先です。

try {
    val fos = FileOutputStream(distFile)
    newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
    fos.close()
} catch (e: IOException) {

}

以上。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1