android文件bitmap,android - Convert Bitmap to File - Stack Overflow

此篇博客介绍了如何在Android AppCompatActivity中,从应用资源加载图片并将其显示在ImageView上,还展示了将图片保存到文件并与UI交互的方法。此外,还包含了从Assets读取文件和异常处理的实用函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Hope this helps u

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

// Get the bitmap from assets and display into image view

val bitmap = assetsToBitmap("tulip.jpg")

// If bitmap is not null

bitmap?.let {

image_view_bitmap.setImageBitmap(bitmap)

}

// Click listener for button widget

button.setOnClickListener{

if(bitmap!=null){

// Save the bitmap to a file and display it into image view

val uri = bitmapToFile(bitmap)

image_view_file.setImageURI(uri)

// Display the saved bitmap's uri in text view

text_view.text = uri.toString()

// Show a toast message

toast("Bitmap saved in a file.")

}else{

toast("bitmap not found.")

}

}

}

// Method to get a bitmap from assets

private fun assetsToBitmap(fileName:String):Bitmap?{

return try{

val stream = assets.open(fileName)

BitmapFactory.decodeStream(stream)

}catch (e:IOException){

e.printStackTrace()

null

}

}

// Method to save an bitmap to a file

private fun bitmapToFile(bitmap:Bitmap): Uri {

// Get the context wrapper

val wrapper = ContextWrapper(applicationContext)

// Initialize a new file instance to save bitmap object

var file = wrapper.getDir("Images",Context.MODE_PRIVATE)

file = File(file,"${UUID.randomUUID()}.jpg")

try{

// Compress the bitmap and save in jpg format

val stream:OutputStream = FileOutputStream(file)

bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream)

stream.flush()

stream.close()

}catch (e:IOException){

e.printStackTrace()

}

// Return the saved bitmap uri

return Uri.parse(file.absolutePath)

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值