【HarmonyOS】模仿个人中心头像图片,调用系统相机拍照,从系统相册选择图片和圆形裁剪显示 (二)

本文主要是介绍【HarmonyOS】模仿个人中心头像图片,调用系统相机拍照,从系统相册选择图片和圆形裁剪显示 (二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

【HarmonyOS】模仿个人中心头像图片,调用系统相机拍照,从系统相册选择图片和圆形裁剪显示 (二)

Demo效果展示:

在这里插入图片描述

方案思路:

1.修改调用相机的方式,使用cameraKit进行相机的调用,拍照后返回图片url进行处理。
2.裁剪View,使用画布进行取景框的效果展示

手势拖动和放大缩小图片,裁剪计算在第三章进行讲解。

Demo示例代码:

UI主界面


import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { image } from '@kit.ImageKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import { router } from '@kit.ArkUI';
import { cameraPicker as picker } from '@kit.CameraKit';
import { camera } from '@kit.CameraKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { CropView } from './CropView';

struct Index {private TAG: string = "imageTest"; mUserPixel: image.PixelMap | undefined = undefined; mTargetPixel: image.PixelMap | undefined = undefined;/*** 拍照获取图片*/private async getPictureFromCamera(){try {let pickerProfile: picker.PickerProfile = {// 相机的位置。cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK};let pickerResult: picker.PickerResult = await picker.pick(getContext(),[picker.PickerMediaType.PHOTO],pickerProfile);console.log(this.TAG, "the pick pickerResult is:" + JSON.stringify(pickerResult));// 成功才处理if(pickerResult && pickerResult.resultCode == 0){await this.getImageByPath(pickerResult.resultUri);}} catch (error) {let err = error as BusinessError;console.error(this.TAG, `the pick call failed. error code: ${err.code}`);}}/*** 相册选择图片*/private async getPictureFromAlbum() {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);let albumPath = photoSelectResult.photoUris[0];console.info(this.TAG, 'getPictureFromAlbum albumPath= ' + albumPath);await this.getImageByPath(albumPath);}/*** 获取图片pixelMap* @param path*/private async getImageByPath(path: string) {console.info(this.TAG, 'getImageByPath path: ' + path);try {// 读取图片为bufferconst file = fs.openSync(path, fs.OpenMode.READ_ONLY);let photoSize = fs.statSync(file.fd).size;console.info(this.TAG, 'Photo Size: ' + photoSize);let buffer = new ArrayBuffer(photoSize);fs.readSync(file.fd, buffer);fs.closeSync(file);// 解码成PixelMapconst imageSource = image.createImageSource(buffer);console.log(this.TAG, 'imageSource: ' + JSON.stringify(imageSource));this.mUserPixel = await imageSource.createPixelMap({});} catch (e) {console.info(this.TAG, 'getImage e: ' + JSON.stringify(e));}}build() {Scroll(){Column() {Text("点击拍照").fontSize(50).fontWeight(FontWeight.Bold).onClick(() => {this.getPictureFromCamera();})Text("相册选择").fontSize(50).fontWeight(FontWeight.Bold).onClick(() => {this.getPictureFromAlbum();})Image(this.mUserPixel).objectFit(ImageFit.Fill).width('100%').aspectRatio(1)Text("图片裁剪").fontSize(50).fontWeight(FontWeight.Bold).onClick(() => {this.cropImage();// router.pushUrl({//   url: "pages/crop"// })})CropView({ mImg: $mUserPixel }).width('100%').aspectRatio(1)Text("裁剪效果").fontSize(50).fontWeight(FontWeight.Bold)Image(this.mTargetPixel).width('100%').aspectRatio(1).borderRadius(200)}.height(3000).width('100%')}.height('100%').width('100%')}private async cropImage(){if(!this.mUserPixel){return;}let cp = await this.copyPixelMap(this.mUserPixel);let region: image.Region = { x: 0, y: 0, size: { width: 400, height: 400 } };cp.cropSync(region);}async copyPixelMap(pixel: PixelMap): Promise<PixelMap> {const info: image.ImageInfo = await pixel.getImageInfo();const buffer: ArrayBuffer = new ArrayBuffer(pixel.getPixelBytesNumber());await pixel.readPixelsToBuffer(buffer);const opts: image.InitializationOptions = {editable: true,pixelFormat: image.PixelMapFormat.RGBA_8888,size: { height: info.size.height, width: info.size.width }};return image.createPixelMap(buffer, opts);}}

CropView 裁剪View


interface LoadResult {width: number;height: number;componentWidth: number;componentHeight: number;loadingStatus: number;contentWidth: number;contentHeight: number;contentOffsetX: number;contentOffsetY: number;
}
export struct CropView {private TAG: string = "CropView";private mRenderingContextSettings: RenderingContextSettings = new RenderingContextSettings(true);private mCanvasRenderingContext2D: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.mRenderingContextSettings); mImg: PixelMap;private onLoadImgComplete = (msg: LoadResult) => {}private onCanvasReady = ()=>{if(!this.mCanvasRenderingContext2D){console.error(this.TAG, "onCanvasReady error mCanvasRenderingContext2D null !");return;}let cr = this.mCanvasRenderingContext2D;// 画布颜色cr.fillStyle = '#AA000000';let height = cr.height;let width = cr.width;cr.fillRect(0, 0, width, height);// 圆形的中心点let centerX = width / 2;let centerY = height / 2;// 圆形半径let radius = Math.min(width, height) / 2 - 100;cr.globalCompositeOperation = 'destination-out'cr.fillStyle = 'white'cr.beginPath();cr.arc(centerX, centerY, radius, 0, 2 * Math.PI);cr.fill();cr.globalCompositeOperation = 'source-over';cr.strokeStyle = '#FFFFFF';cr.beginPath();cr.arc(centerX, centerY, radius, 0, 2 * Math.PI);cr.closePath();cr.lineWidth = 1;cr.stroke();}build() {Stack() {// 黑色底图Row().width("100%").height("100%").backgroundColor(Color.Black)// 用户图Image(this.mImg).objectFit(ImageFit.Fill).width('100%').aspectRatio(1).onComplete(this.onLoadImgComplete)// 取景框Canvas(this.mCanvasRenderingContext2D).width('100%').height('100%').backgroundColor(Color.Transparent).onReady(this.onCanvasReady).clip(true).backgroundColor("#00000080")}.width("100%").height("100%")}
}

这篇关于【HarmonyOS】模仿个人中心头像图片,调用系统相机拍照,从系统相册选择图片和圆形裁剪显示 (二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1121809

相关文章

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Deepseek R1模型本地化部署+API接口调用详细教程(释放AI生产力)

《DeepseekR1模型本地化部署+API接口调用详细教程(释放AI生产力)》本文介绍了本地部署DeepSeekR1模型和通过API调用将其集成到VSCode中的过程,作者详细步骤展示了如何下载和... 目录前言一、deepseek R1模型与chatGPT o1系列模型对比二、本地部署步骤1.安装oll

在不同系统间迁移Python程序的方法与教程

《在不同系统间迁移Python程序的方法与教程》本文介绍了几种将Windows上编写的Python程序迁移到Linux服务器上的方法,包括使用虚拟环境和依赖冻结、容器化技术(如Docker)、使用An... 目录使用虚拟环境和依赖冻结1. 创建虚拟环境2. 冻结依赖使用容器化技术(如 docker)1. 创

一分钟带你上手Python调用DeepSeek的API

《一分钟带你上手Python调用DeepSeek的API》最近DeepSeek非常火,作为一枚对前言技术非常关注的程序员来说,自然都想对接DeepSeek的API来体验一把,下面小编就来为大家介绍一下... 目录前言免费体验API-Key申请首次调用API基本概念最小单元推理模型智能体自定义界面总结前言最

Python利用PIL进行图片压缩

《Python利用PIL进行图片压缩》有时在发送一些文件如PPT、Word时,由于文件中的图片太大,导致文件也太大,无法发送,所以本文为大家介绍了Python中图片压缩的方法,需要的可以参考下... 有时在发送一些文件如PPT、Word时,由于文件中的图片太大,导致文件也太大,无法发送,所有可以对文件中的图

java获取图片的大小、宽度、高度方式

《java获取图片的大小、宽度、高度方式》文章介绍了如何将File对象转换为MultipartFile对象的过程,并分享了个人经验,希望能为读者提供参考... 目China编程录Java获取图片的大小、宽度、高度File对象(该对象里面是图片)MultipartFile对象(该对象里面是图片)总结java获取图片

JAVA调用Deepseek的api完成基本对话简单代码示例

《JAVA调用Deepseek的api完成基本对话简单代码示例》:本文主要介绍JAVA调用Deepseek的api完成基本对话的相关资料,文中详细讲解了如何获取DeepSeekAPI密钥、添加H... 获取API密钥首先,从DeepSeek平台获取API密钥,用于身份验证。添加HTTP客户端依赖使用Jav

CentOS系统Maven安装教程分享

《CentOS系统Maven安装教程分享》本文介绍了如何在CentOS系统中安装Maven,并提供了一个简单的实际应用案例,安装Maven需要先安装Java和设置环境变量,Maven可以自动管理项目的... 目录准备工作下载并安装Maven常见问题及解决方法实际应用案例总结Maven是一个流行的项目管理工具

Java实战之自助进行多张图片合成拼接

《Java实战之自助进行多张图片合成拼接》在当今数字化时代,图像处理技术在各个领域都发挥着至关重要的作用,本文为大家详细介绍了如何使用Java实现多张图片合成拼接,需要的可以了解下... 目录前言一、图片合成需求描述二、图片合成设计与实现1、编程语言2、基础数据准备3、图片合成流程4、图片合成实现三、总结前

使用Python实现图片和base64转换工具

《使用Python实现图片和base64转换工具》这篇文章主要为大家详细介绍了如何使用Python中的base64模块编写一个工具,可以实现图片和Base64编码之间的转换,感兴趣的小伙伴可以了解下... 简介使用python的base64模块来实现图片和Base64编码之间的转换。可以将图片转换为Bas