如何在React Native中优化图像

时间:2016-06-05 07:09:35

标签: image compression react-native

通过相机拍摄的照片太大,无法在React原生中有效上传和下载。

是否有api或库来压缩React Native中的PNG图像文件?

4 个答案:

答案 0 :(得分:12)

如果您使用react-native-image-picker上传图像,则可以设置maxWidth,maxHeight或图像质量以减小尺寸。

 const options = {
                    title: 'Select Picture',
                    storageOptions: {
                        skipBackup: true,
                        path: 'images',

                    },
                    maxWidth: 500,
                    maxHeight: 500,
                    quality: 0.5
                };
ImagePicker.showImagePicker(options, resolve, reject);

答案 1 :(得分:4)

https://github.com/bamlab/react-native-image-resizer提供了一个用于调整本地图像大小的API。

它允许您指定:

  • 最大尺寸(同时保持纵横比)和;
  • 输出质量(仅限JPEG)

<强> 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.
});

答案 2 :(得分:1)

您可以使用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 }
};

答案 3 :(得分:0)

尽管它仅适用于android,但它是我使用的出色插件 Npm js url for plugin

npm install --save react-native-compress-image
react-native link react-native-compress-image

用法

import CompressImage from 'react-native-compress-image';

CompressImage.createCompressedImage(imageUri, appDirectory).then((response) => {

// response.uri is the URI of the new image that can now be displayed, uploaded...
// response.path is the path of the new image
// response.name is the name of the new image with the extension
// response.size is the size of the new image
}).catch((err) => {
// Oops, something went wrong. Check that the filename is correct and
// inspect err to get more details.
});




CompressImage.createCustomCompressedImage(imageUri, appDirectory, maxWidth, maxHeight, quality).then((response) => {
  // response.uri is the URI of the new image that can now be displayed, uploaded...
  // response.path is the path of the new image
  // response.name is the name of the new image with the extension
  // response.size is the size of the new image
}).catch((err) => {
  // Oops, something went wrong. Check that the filename is correct and
  // inspect err to get more details.
});