上传图片
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
import HashMap from '@ohos.util.HashMap';
|
||||
import { Base64Util } from './Base64Util';
|
||||
import { CryptoJS } from '@ohos/crypto-js';
|
||||
import { logger } from './logger';
|
||||
import image from '@ohos.multimedia.image';
|
||||
import fs from '@ohos.file.fs';
|
||||
|
||||
|
||||
export class ChangeUtil {
|
||||
@@ -54,5 +57,66 @@ export class ChangeUtil {
|
||||
return reg2.test(password);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将图片转换为base64字符串
|
||||
* @param imageUri 图片URI
|
||||
* @returns Promise<string> base64字符串
|
||||
*/
|
||||
static async imageToBase64(imageUri: string): Promise<string> {
|
||||
// 1. 验证URI有效性
|
||||
if (!imageUri || !imageUri.startsWith('file://')) {
|
||||
throw new Error('无效的图片URI,必须以file://开头');
|
||||
}
|
||||
let imageSource: image.ImageSource | undefined;
|
||||
let pixelMap: image.PixelMap | undefined;
|
||||
let imagePacker: image.ImagePacker | undefined;
|
||||
try {
|
||||
const file = fs.openSync(imageUri, fs.OpenMode.READ_ONLY);
|
||||
const imageSource = image.createImageSource(file.fd);
|
||||
if (!imageSource) {
|
||||
throw new Error('创建ImageSource失败,请检查图片路径');
|
||||
}
|
||||
logger.info('正在获取图片信息...');
|
||||
const imageInfo = await imageSource.getImageInfo();
|
||||
logger.info(`图片尺寸: ${imageInfo.size.width}x${imageInfo.size.height}`);
|
||||
pixelMap = await imageSource.createPixelMap({
|
||||
desiredSize: {
|
||||
width: imageInfo.size.width,
|
||||
height: imageInfo.size.height
|
||||
}
|
||||
});
|
||||
if (!pixelMap) {
|
||||
throw new Error('创建PixelMap失败');
|
||||
}
|
||||
// 5. 压缩图片
|
||||
imagePacker = image.createImagePacker();
|
||||
const packOpts: image.PackingOption = {
|
||||
format: "image/jpeg",
|
||||
quality: 80 // 适当提高质量保证清晰度
|
||||
};
|
||||
logger.info('正在压缩图片...');
|
||||
const arrayBuffer = await imagePacker.packing(pixelMap, packOpts);
|
||||
const unit8Array = new Uint8Array(arrayBuffer);
|
||||
let binary = '';
|
||||
unit8Array.forEach(byte => {
|
||||
binary += String.fromCharCode(byte);
|
||||
});
|
||||
const base64String = Base64Util.encodeToStrSync(binary);
|
||||
logger.info(`图片转换成功,大小: ${Math.round(base64String.length / 1024)}KB`);
|
||||
return base64String;
|
||||
} catch (error) {
|
||||
logger.error('图片处理失败: ' + JSON.stringify(error));
|
||||
throw new Error(`图片处理失败: ${error.message}`);
|
||||
} finally {
|
||||
// 7. 确保释放资源
|
||||
try {
|
||||
pixelMap?.release();
|
||||
imageSource?.release();
|
||||
imagePacker?.release();
|
||||
} catch (e) {
|
||||
logger.error('资源释放异常: ' + JSON.stringify(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -7,8 +7,6 @@ import { HashMap } from '@kit.ArkTS';
|
||||
import { CryptoJS } from '@ohos/crypto-js'
|
||||
import { Base64Util } from './Base64Util';
|
||||
import { ChangeUtil } from './ChangeUtil'
|
||||
import { BasicConstant } from '../constants/BasicConstant'
|
||||
import image from '@ohos.multimedia.image';
|
||||
|
||||
interface HdRequestOptions {
|
||||
baseURL?: string
|
||||
@@ -270,114 +268,6 @@ class HdHttp {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传图片方法
|
||||
* @param url 上传地址
|
||||
* @param imageUri 图片URI
|
||||
* @param params 其他参数
|
||||
* @returns Promise<HdResponse<T>>
|
||||
*/
|
||||
async uploadImage<T>(url: string, imageUrl: string): Promise<HdResponse<T>> {
|
||||
try {
|
||||
// 1. 读取图片文件并转换为base64
|
||||
const imageBase64 = await this.imageToBase64(imageUrl);
|
||||
|
||||
// 2. 准备上传参数
|
||||
const uploadParams: UploadImageParams = {
|
||||
uuid: authStore.getUser().uuid || '',
|
||||
userName: authStore.getUser().userName || '',
|
||||
photo: imageBase64,
|
||||
type: '2' // 根据业务需求设置类型
|
||||
};
|
||||
|
||||
// 3. 转换为HashMap格式 - 使用类型安全的方式
|
||||
const hashMap = new HashMap<string, string>();
|
||||
hashMap.set('uuid', uploadParams.uuid);
|
||||
hashMap.set('userName', uploadParams.userName);
|
||||
hashMap.set('photo', uploadParams.photo);
|
||||
hashMap.set('type', uploadParams.type);
|
||||
|
||||
// 4. 调用posts方法上传
|
||||
return this.posts<T>(url, hashMap);
|
||||
} catch (error) {
|
||||
logger.error('uploadImage error:' + JSON.stringify(error));
|
||||
promptAction.showToast({ message: '图片上传失败' });
|
||||
return Promise.reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将图片转换为base64字符串
|
||||
* @param imageUri 图片URI
|
||||
* @returns Promise<string> base64字符串
|
||||
*/
|
||||
private async imageToBase64(imageUrl: string): Promise<string> {
|
||||
// 1. 验证URI有效性
|
||||
if (!imageUrl || !imageUrl.startsWith('file://')) {
|
||||
throw new Error('无效的图片URI,必须以file://开头');
|
||||
}
|
||||
let imageSource: image.ImageSource | undefined;
|
||||
let pixelMap: image.PixelMap | undefined;
|
||||
let imagePacker: image.ImagePacker | undefined;
|
||||
try {
|
||||
// 2. 创建ImageSource(添加错误处理)
|
||||
imageSource = image.createImageSource(imageUrl);
|
||||
if (!imageSource) {
|
||||
throw new Error('创建ImageSource失败,请检查图片路径');
|
||||
}
|
||||
|
||||
// 3. 获取图片信息(添加详细日志)
|
||||
logger.info('正在获取图片信息...');
|
||||
const imageInfo = await imageSource.getImageInfo();
|
||||
logger.info(`图片尺寸: ${imageInfo.size.width}x${imageInfo.size.height}`);
|
||||
|
||||
// 4. 创建PixelMap
|
||||
pixelMap = await imageSource.createPixelMap({
|
||||
desiredSize: {
|
||||
width: imageInfo.size.width,
|
||||
height: imageInfo.size.height
|
||||
}
|
||||
});
|
||||
if (!pixelMap) {
|
||||
throw new Error('创建PixelMap失败');
|
||||
}
|
||||
|
||||
// 5. 压缩图片
|
||||
imagePacker = image.createImagePacker();
|
||||
const packOpts: image.PackingOption = {
|
||||
format: "image/jpeg",
|
||||
quality: 80 // 适当提高质量保证清晰度
|
||||
};
|
||||
|
||||
logger.info('正在压缩图片...');
|
||||
const arrayBuffer = await imagePacker.packing(pixelMap, packOpts);
|
||||
|
||||
// 6. 转换为base64
|
||||
const unit8Array = new Uint8Array(arrayBuffer);
|
||||
let binary = '';
|
||||
unit8Array.forEach(byte => {
|
||||
binary += String.fromCharCode(byte);
|
||||
});
|
||||
|
||||
const base64String = Base64Util.encodeToStrSync(binary);
|
||||
logger.info(`图片转换成功,大小: ${Math.round(base64String.length / 1024)}KB`);
|
||||
return base64String;
|
||||
|
||||
} catch (error) {
|
||||
logger.error('图片处理失败: ' + JSON.stringify(error));
|
||||
throw new Error(`图片处理失败: ${error.message}`);
|
||||
} finally {
|
||||
// 7. 确保释放资源
|
||||
try {
|
||||
pixelMap?.release();
|
||||
imageSource?.release();
|
||||
imagePacker?.release();
|
||||
} catch (e) {
|
||||
logger.error('资源释放异常: ' + JSON.stringify(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface UploadImageParams {
|
||||
|
||||
Reference in New Issue
Block a user