在项目中可能会有保存网页生成二维码,然后将二维码图片保存到相册的需求,这里就写了一个demo,做了这样的功能,效果图如下:
首先,引入二维码zxing库:
implementation 'com.google.zxing:zxing-parent:3.4.1'
implementation 'com.google.zxing:core:3.3.3'
点击生成二维码图片:
/**
* 生成二维码图片
*
* @param str 二维码内容
* @return
*/
private fun createBitcode(str: String?): Bitmap? {
var bitmap: Bitmap? = null
var result: BitMatrix? = null
val multiFormatWriter = MultiFormatWriter()
try {
result = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 260, 260)
val w: Int = result.width
val h: Int = result.height
val pixels = IntArray(w * h)
for (y in 0 until h) {
val offset = y * w
for (x in 0 until w) {
pixels[offset + x] = if (result.get(x, y)) Color.BLACK else Color.WHITE
}
}
bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
bitmap.setPixels(pixels, 0, w, 0, 0, w, h)
} catch (e: WriterException) {
e.printStackTrace()
} catch (e: IllegalArgumentException) {
e.printStackTrace()
}
return bitmap
}
点击保存二维码图片到相册:
btnSave?.setOnClickListener {
ivQrCode?.let { iv->
saveBitmap(iv.drawable!!.toBitmap(iv.width, iv.height, Bitmap.Config.RGB_565), editText?.text.toString())
}
}
/**
* 将bitmap保存到相册
*/
private fun saveBitmap(bitmap: Bitmap, url: String) {
try {
val path: String = getFilePath()
if (!TextUtils.isEmpty(path)) {
val name = path + File.separator + handleFileName(url) + ".jpg"
val fos = FileOutputStream(name)
if (bitmap.compress(CompressFormat.WEBP, 100, fos)) {
fos.flush()
fos.close()
bitmap.recycle()
} else {
Toast.makeText(applicationContext, "保存失败", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(applicationContext, "白村失败", Toast.LENGTH_SHORT).show()
}
} catch (e: FileNotFoundException) {
Toast.makeText(applicationContext, "保存失败", Toast.LENGTH_SHORT).show()
}
}
/**
* 获取相册截图文件夹,这里将截图保存到/DCIM/Screenshots/路径
*/
private fun getFilePath(): String {
val sdCardExist = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
if (sdCardExist) {
val path = Environment.getExternalStorageDirectory().toString() + "/DCIM/Screenshots/"
val dir = File(path)
if (!dir.exists()) {
dir.mkdirs()
}
return dir.absolutePath
}
return ""
}
这里将保存的文件名对一些符号就行截取:
private fun handleFileName(s: String): String? {
var res = s
res.replace("\\s*".toRegex(), "")
if (res.contains("/")) {
res = res.substring(0, s.indexOf("/"))
}
if (res.contains("-")) {
res = res.substring(0, s.indexOf("-"))
}
if (res.contains(":")) {
res = res.substring(0, s.indexOf(":"))
}
return res
}
网友评论