思路 拉起相册 选择照片 获取图片路径 读取照片转成buffer 解码成PixeMap 转换成base64
在库中存储的就是照片的base64
废话不多说 看源码
先看图解 确保能操作成功
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { image } from '@kit.ImageKit';
import { buffer } from '@kit.ArkTS';
import { relationalStore, ValuesBucket } from '@kit.ArkData'
interface NoteItem extends ValuesBucket {
id: number | null
image1: string
}
@Entry
@Component
struct Index {
@State getAlbum: string = '显示相册中的图片';
@State pixel: image.PixelMap | undefined = undefined;
//图片地址
@State albumPath: string = '';
@State photoSize: number = 0;
@State message: string = 'PixelMapToBase64';
@State base64: string = '';
//数据库结果集
@State list: NoteItem [] = []
// 表名
tableName: string = 'ceshiTable1'
sqlCreate: string = `CREATE TABLE IF NOT EXISTS ${this.tableName} (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"image1" TEXT
)`
// 操作数据库的管理对象
store: relationalStore.RdbStore | null = null
//拉起相册 展示
async example03() {
// 拉起相册,选择图片 获取路径
let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
PhotoSelectOptions.maxSelectNumber = 1;
let photoPicker = new photoAccessHelper.PhotoViewPicker();
let photoSelectResult: photoAccessHelper.PhotoSelectResult = await photoPicker.select(PhotoSelectOptions)
this.albumPath = photoSelectResult.photoUris[0] //图片路径
// 读取图片为buffer
const file = fs.openSync(this.albumPath, fs.OpenMode.READ_ONLY);
this.photoSize = fs.statSync(file.fd).size;
let imageBuffer = new ArrayBuffer(this.photoSize);
fs.readSync(file.fd, imageBuffer);
fs.closeSync(file);
// 解码成PixelMap
const imageSource = image.createImageSource(imageBuffer);
console.log('imageSource: ' + JSON.stringify(imageSource));
let pixelMap = await imageSource.createPixelMap({});
// 转换成base64 !!!!!注意图片格式 这里用的是jpeg 可以在相册照片详情查看照片格式
const imagePackerApi: image.ImagePacker = image.createImagePacker();
let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 100 };
imagePackerApi.packing(pixelMap, packOpts).then((data: ArrayBuffer) => {
let buf: buffer.Buffer = buffer.from(data);
this.base64 = 'data:image/jpeg;base64,' + buf.toString('base64', 0, buf.length);
console.info('base64: ' + this.base64);
})
}
// 获取数据库管理对象
async getStoreInstance() {
// 如果已经存在,直接返回
if (this.store) {
return this.store
}
// 获取操作数据库的管理对象(如果数据库文件不存在,会自动创建数据库文件)
this.store = await relationalStore.getRdbStore(getContext(), {
name: 'rdb.db', // 数据库文件名
securityLevel: relationalStore.SecurityLevel.S1, // 数据库安全级别
})
// 返回 store 对象
return this.store
}
build() {
Scroll() {
Row() {
Column() {
// Image(this.pixel)
// .width('50%')
// .height('50%' )
Text(this.base64.length.toString()).fontSize(10)
Image(this.base64)
.width(200).height(200).margin(15)
.aspectRatio(1)
Image($rawfile(this.albumPath))
Button('选择图片').onClick((event: ClickEvent) => {
this.example03()
})
Button('创建数据库文件')
.onClick(async () => {
// 获取操作数据库的管理对象(如果数据库文件不存在,会自动创建数据库文件)
const store = await relationalStore.getRdbStore(getContext(), {
name: 'RDB.db', // 数据库文件名
securityLevel: relationalStore.SecurityLevel.S1, // 数据库安全级别
})
// 执行创建表的语句 execute 执行
store.executeSql(this.sqlCreate)
AlertDialog.show({ message: '创建成功' })
})
Button('创建数据表')
.onClick(async () => {
const store = await this.getStoreInstance()
store.executeSql(this.sqlCreate)
AlertDialog.show({ message: '创建成功' })
})
Button('查询数据库表的字段')
.onClick(async () => {
// 获取操作数据库的对象
const store = await this.getStoreInstance()
// 谓词(条件),谓词类需要 new 实例化,传入表名 privacy_note
const predicates = new relationalStore.RdbPredicates(this.tableName)
// query 查询,传入必传参数 谓词
const resultSet = await store.query(predicates)
AlertDialog.show({ message: '数据库的字段名:' + resultSet.columnNames })
})
Button('新建一条数据')
.onClick(async () => {
// 获取操作数据库的对象
const store = await this.getStoreInstance()
// 添加一条数据
const id = await store.insert(this.tableName, {
id: null,
image1: this.base64,
} as NoteItem)
AlertDialog.show({ message: '新增数组成功,数据的id为:' + id })
// 批量添加,传入数组
// store.batchInsert(表名, 数组)
})
Button('查询所有数据')
.onClick(async () => {
// 获取操作数据库的对象
const store = await this.getStoreInstance()
// 谓词(条件)
const predicates = new relationalStore.RdbPredicates(this.tableName)
predicates.orderByDesc('id') // 倒序(由大到小,常用于排序)
// resultSet 结果集
const resultSet = await store.query(predicates)
// 准备一个数组,用于存储数据库提取的数据
// resultSet.goToNextRow() 指针移动到下一行
while (resultSet.goToNextRow()) {
// 移动指针的时候提取数据,按列下标提取数据
this.list.push({
// resultSet.getColumnIndex() 根据列名称获取下标(索引)
id: resultSet.getLong(resultSet.getColumnIndex('id')),
image1: resultSet.getString(resultSet.getColumnIndex('image1')),
})
}
})
}
.width('30%')
Column() {
Row() {
ForEach(this.list,(item : NoteItem)=>{
Row(){
if (item.image1 != '') {
Image(item.image1).width('20%').height('20%')
}
}
})
}
}
.width('70%')
}
}
.height('100%')
}
}