鸿蒙中调用相机,相册,抖动
温馨提示:本文最后更新于2024年11月18日 07:41,若内容或图片失效,请在下方留言或联系博主。
1. 调用相册
import { camera, cameraPicker } from '@kit.CameraKit';
import fs from '@ohos.file.fs';
import { util } from '@kit.ArkTS';
class CameraPlugin {
async pickerCamera() {
// 1. 打开相机后置摄像头得到拍照结果集
const pickerProfile: cameraPicker.PickerProfile = {
cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK
};
const pickerResult: cameraPicker.PickerResult = await cameraPicker.pick(getContext(),
[cameraPicker.PickerMediaType.PHOTO], pickerProfile);
// 2. 根据结果集的URI属性同步打开文件
const file = fs.openSync(pickerResult.resultUri)
// 3. 同步读取文件的详情信息
const stat = fs.statSync(file.fd)
// 4. 定义缓冲区用于保存读取的文件
const buffer = new ArrayBuffer(stat.size)
// 5. 开始同步读取内容到缓冲区
fs.readSync(file.fd, buffer)
// 6. 读取完毕后关闭文件流
fs.closeSync(file)
// 7. 借助util工具方法把读取的文件流转成base64编码的字符串
const helper = new util.Base64Helper()
const str = helper.encodeToStringSync(new Uint8Array(buffer))
console.log('mk-logger', 'pickerCamera', str)
return str
}
}
export const cameraPlugin = new CameraPlugin()
2. 调用相册
import { picker } from '@kit.CoreFileKit'
import fs from '@ohos.file.fs';
import { util } from '@kit.ArkTS';
class PhotoPlugin {
async pickerPhoto(){
// 1. 打开相册选择图片
const photoSelectOptions = new picker.PhotoSelectOptions()
photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
photoSelectOptions.maxSelectNumber = 1;
const photoPicker = new picker.PhotoViewPicker();
const res = await photoPicker.select(photoSelectOptions)
console.log('mk-logger', 'photoPlugin', JSON.stringify(res))
// 2. 文件操作
// 2.1 获取照片的uri地址
const uri = res.photoUris[0]
// 2.2 根据uri同步打开文件
const file = fs.openSync(uri)
// 2.3 同步获取文件的详细信息
const stat = fs.statSync(file.fd)
// 2.4 创建缓冲区存储读取的文件流
const buffer = new ArrayBuffer(stat.size)
// 2.5 开始同步读取文件流到缓冲区
fs.readSync(file.fd, buffer)
// 2.6 关闭文件流
fs.closeSync(file)
// 3. 转成base64编码的字符串
const helper = new util.Base64Helper()
const str = helper.encodeToStringSync(new Uint8Array(buffer))
console.log('mk-logger', 'photoPlugin-str', str)
return str
}
}
export const photoPlugin = new PhotoPlugin()
3. 调用抖动
import { vibrator } from '@kit.SensorServiceKit'
class SensorPlugin {
vibrator() {
vibrator.startVibration({ type: 'time', duration: 50 }, { usage: 'touch' })
}
}
export const sensorPlugin = new SensorPlugin()