如何将本地图片存入MySQL中_如何将图片存入数据库中

这篇博客介绍了如何将Android本地的Bitmap图片转换成byte数组,并存入SQLite或MySQL数据库。首先,通过BitmapFactory将图片资源转为Bitmap,然后压缩成byte数组。接着,将byte数组存储到ContentValues,最后执行数据库的插入操作。
摘要由CSDN通过智能技术生成

前两天有人在校论坛上问过,我搜了些相关信息,然后自己总结了一个做法,记录如下,以备日后使用

1.将图片转化为byte数组

2.将byte数组放入contentvalues

3.执行数据库的insert操作,将contentvalues里面的值存入sqlite

代码大致如下:

//转换

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

bm.compress(Bitmap.CompressFormat.PNG, 100, baos);

byte[] result = baos.toByteArray();

//装入

ContentValues values = new ContentValues();

values.put("image", result);

//插入数据库

db.insert("image_info", "image", values);

Android中Bitmap, Drawable, Byte之间的转化

1.  Bitmap 转化为 byte

ByteArrayOutputStream out = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);

byte[] array= out.toByteArray();

2. byte转化为bitmap

final ContentResolver contentResolver = context.getContentResolver();

final PackageManager manager = context.getPackageManager();

final Cursor c = contentResolver.query(uri, null, null, null, null);

final int icon3DIndex = c.getColumnIndexOrThrow(ColumnName);

byte[] data = c.getBlob(icon3DIndex);

Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

3. bitmap转化为Drawable

Drawable drawable = new FastBitmapDrawable(bitmap);

...

4. Drawable转化为bitmap

a. BitmapDrawable, FastBitmapDrawable直接用getBitmap

b. 其他类型的Drawable用Canvas画到一个bitmap上

Canvas canvas = new Canvas(bitmap)

drawable.draw(canvas);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值