Android保存图片到数据库

本文介绍两种在Android系统中保存图标的实用方法。方法一通过将Bitmap压缩为PNG格式并存储到SQLite数据库的BLOB字段中实现。方法二利用ContentResolver和MediaStore API,将图片保存至指定的content:URI路径。

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

    闲话不多说,先看代码

    方法一:

public void saveIcon(Bitmap icon) {
		if (icon == null) {
			return;
		}

		// 最终图标要保存到浏览器的内部数据库中,系统程序均保存为SQLite格式,Browser也不例外,因为图片是二进制的所以使用字节数组存储数据库的
		// BLOB类型
		final ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 将Bitmap压缩成PNG编码,质量为100%存储		
        icon.compress(Bitmap.CompressFormat.PNG, 100, os); 
        // 构造SQLite的Content对象,这里也可以使用raw
		ContentValues values = new ContentValues(); 
		// 写入数据库的Browser.BookmarkColumns.TOUCH_ICON字段
		values.put(Browser.BookmarkColumns.TOUCH_ICON, os.toByteArray()); 
		
		DBUtil.update(....);//调用更新或者插入到数据库的方法
	}

   方法二:如果数据表入口时一个content:URI

 

import android.provider.MediaStore.Images.Media;
import android.content.ContentValues;
import java.io.OutputStream;

// Save the name and description of an image in a ContentValues map.  
ContentValues values = new ContentValues(3);
values.put(Media.DISPLAY_NAME, "road_trip_1");
values.put(Media.DESCRIPTION, "Day 1, trip to Los Angeles");
values.put(Media.MIME_TYPE, "image/jpeg");

// Add a new record without the bitmap, but with the values just set.
// insert() returns the URI of the new record.
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);

// Now get a handle to the file for that record, and save the data into it.
// Here, sourceBitmap is a Bitmap object representing the file to save to the database.
try {
    OutputStream outStream = getContentResolver().openOutputStream(uri);
    sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
    outStream.close();
} catch (Exception e) {
    Log.e(TAG, "exception while writing image", e);
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值