通过相机拍摄的照片在React Native中上传和下载效率太低。
是否有一种API或库可以在React Native中压缩PNG图像文件?
通过相机拍摄的照片在React Native中上传和下载效率太低。
是否有一种API或库可以在React Native中压缩PNG图像文件?
如果您使用react-native-image-picker上传图片,您可以设置图片的最大宽度、最大高度或图像质量来减小图片大小。
const options = {
title: 'Select Picture',
storageOptions: {
skipBackup: true,
path: 'images',
},
maxWidth: 500,
maxHeight: 500,
quality: 0.5,
};
ImagePicker.showImagePicker(options, resolve, reject);
https://github.com/bamlab/react-native-image-resizer 提供了一个API来调整本地图片的大小。
它允许你指定:
API
import ImageResizer from 'react-native-image-resizer';
ImageResizer.createResizedImage(
imageUri,
newWidth,
newHeight,
compressFormat,
quality,
)
.then(resizedImageUri => {
// resizeImageUri is the URI of the new image that can now be displayed, uploaded...
})
.catch(err => {
// Oops, something went wrong. Check that the filename is correct and
// inspect err to get more details.
});
你可以使用expo-image-manipulator:
import { manipulateAsync, SaveFormat } from 'expo-image-manipulator';
const compressImage = async (uri, format = SaveFormat.JPEG) => { // SaveFormat.PNG
const result = await manipulateAsync(
uri,
[{ resize: { width: 1200 } }],
{ compress: 0.7, format }
);
return { name: `${Date.now()}.${format}`, type: `image/${format}`, ...result };
// return: { name, type, width, height, uri }
};
我基于图片大小开发了一个在React Native中进行图像压缩的自定义解决方案。
import * as ImageManipulator from 'expo-image-manipulator';
export default async function ImageCompress(image, { width, height }) {
const compressSizer = size => {
const MB = size / Math.pow(1024, 2);
if (Math.round(MB) === 0) return 1;
if (Math.round(MB) === 1) return 0.9;
if (Math.round(MB) === 2) return 0.8;
if (Math.round(MB) === 3) return 0.7;
if (Math.round(MB) === 4) return 0.6;
if (Math.round(MB) >= 5) return 0.5;
if (Math.round(MB) >= 10) return 0.4;
if (Math.round(MB) >= 15) return 0.3;
if (Math.round(MB) >= 20) return 0.2;
if (Math.round(MB) >= 25) return 0.1;
};
const imageManipulator = async (image, { width, height }) => {
const response = await fetch(image);
const blob = await response.blob();
const compress = compressSizer(blob.size);
let resize;
if (height === width) resize = { height: 480, width: 480 };
else if (height > width) resize = { height: 480 };
else resize = { width: 720 };
const compressedPhoto = await ImageManipulator.manipulateAsync(
image,
[{ resize }],
{
compress,
format: ImageManipulator.SaveFormat.JPEG,
},
);
return compressedPhoto.uri;
};
try {
return await imageManipulator(image, { width, height });
} catch (error) {
console.log(error);
}
}