Android 合成兩張圖片並存到手機相簿
我們有時候會需要把兩張圖片合在一起,這時候我們就會用到圖層關係,我們把要當底層的圖片先放在Canvas,接著再把另外一張覆蓋在上面,前提是那張圖片是有透明背景的,這樣才能透到下面的底層圖片。
文章目錄
- 獲取圖片並轉成Bitmap
- 合成兩張圖片
- 儲存到手機相簿
- 程式碼範例
- 效果展示
- Github
1.獲取圖片並轉成Bitmap
//背景圖片
val bgBitmap = BitmapFactory.decodeResource(resources, R.drawable.bg)
//前景圖片
val coinBitmap = BitmapFactory.decodeResource(resources, R.drawable.coin)
2.合成兩張圖片
//將背景圖在塗層最底下
val bitmap = backBitmap.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(bitmap)
val baseRect = Rect(0, 0, backBitmap.width, backBitmap.height)
val frontRect = Rect(0, 0, frontBitmap.width, frontBitmap.height)
canvas.drawBitmap(frontBitmap, frontRect, baseRect, null)
3.儲存到手機相簿
val contentValues = ContentValues()
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis())
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
val uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
uri?.apply {
val ops = contentResolver.openOutputStream(this)
//把Bitmap除存到手機相簿
mergeBitmap(bgBitmap, coinBitmap).compress(Bitmap.CompressFormat.JPEG, 100, ops)
ops?.close()
}
4.程式碼範例
package com.example.compositepicturedemo
import android.content.ContentValues
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Rect
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.ImageView
class MainActivity : AppCompatActivity() {
private lateinit var bgBitmap: Bitmap
private lateinit var coinBitmap: Bitmap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val photoOne = findViewById<ImageView>(R.id.photo_one)
val photoResult = findViewById<ImageView>(R.id.photo_two)
bgBitmap = BitmapFactory.decodeResource(resources, R.drawable.bg)
photoOne.setImageBitmap(bgBitmap)
coinBitmap = BitmapFactory.decodeResource(resources, R.drawable.coin)
photoResult.setImageBitmap(coinBitmap)
}
private fun mergeBitmap(backBitmap: Bitmap, frontBitmap: Bitmap): Bitmap {
val bitmap = backBitmap.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(bitmap)
val baseRect = Rect(0, 0, backBitmap.width, backBitmap.height)
val frontRect = Rect(0, 0, frontBitmap.width, frontBitmap.height)
canvas.drawBitmap(frontBitmap, frontRect, baseRect, null)
return bitmap
}
fun merge(view: View) {
val contentValues = ContentValues()
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis())
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
val uri =
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
uri?.apply {
val ops = contentResolver.openOutputStream(this)
mergeBitmap(bgBitmap, coinBitmap).compress(Bitmap.CompressFormat.JPEG, 100, ops)
ops?.close()
}
}
}
5.效果展示
6.Github
Android 合成兩張圖片並存到手機相簿 Github