【问题标题】:How to save an image to a variable using url react native [closed]如何使用 url react native 将图像保存到变量 [关闭]
【发布时间】:2021-09-21 00:18:05
【问题描述】:

如何将来自url的图像保存在变量中并在下面这个示例中的Image组件中使用它我可以直接加载它,但我想创建一个函数将其存储在变量中并使用离线图像

import React from 'react';
import { View, Image, StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  container: {
    paddingTop: 50,
  },
  tinyLogo: {
    width: 50,
    height: 50,
  },
  logo: {
    width: 66,
    height: 58,
  },
});

const DisplayAnImage = () => {
  return (
    <View style={styles.container}>
    
      <Image
        style={styles.tinyLogo}
        source={{
          uri: 'https://reactnative.dev/img/tiny_logo.png',
        }}
      />
   
     
    </View>
  );
}

export default DisplayAnImage;

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    无需将网址“保存”在变量中。

    只需将url赋值给一个变量,例如:

    const imageUri = 'https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.laramind.com%2Fblog%2Fpercorso-react-native-dal-livello-base-al -livello-avanzato%2F&psig=AOvVaw2Kb7DOrxfQ9hHdyuf-9m49&ust=1626099973147000&source=images&cd=vfe&ved=0CAoQjRxqFwoTCLDDv8yc2_ECFQAAAAAdAAAAABAD'

    并在您的图像组件中使用它:

    要离线使用它,您需要使用外部库,例如 rn-fetch-blob,这里有一个示例应用说明如何使用它:

    // How to Download an Image in React Native from any URL
    // https://aboutreact.com/download-image-in-react-native/
    
    // Import React
    import React from 'react';
    
    // Import Required Components
    import {
      StyleSheet,
      Text,
      View,
      TouchableOpacity,
      PermissionsAndroid,
      Image,
      Platform,
    } from 'react-native';
    
    // Import RNFetchBlob for the file download
    import RNFetchBlob from 'rn-fetch-blob';
    
    const App = () => {
      const REMOTE_IMAGE_PATH =
        'https://raw.githubusercontent.com/AboutReact/sampleresource/master/gift.png'
      const checkPermission = async () => {
        
        // Function to check the platform
        // If iOS then start downloading
        // If Android then ask for permission
    
        if (Platform.OS === 'ios') {
          downloadImage();
        } else {
          try {
            const granted = await PermissionsAndroid.request(
              PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
              {
                title: 'Storage Permission Required',
                message:
                  'App needs access to your storage to download Photos',
              }
            );
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
              // Once user grant the permission start downloading
              console.log('Storage Permission Granted.');
              downloadImage();
            } else {
              // If permission denied then show alert
              alert('Storage Permission Not Granted');
            }
          } catch (err) {
            // To handle permission related exception
            console.warn(err);
          }
        }
      };
    
      const downloadImage = () => {
        // Main function to download the image
        
        // To add the time suffix in filename
        let date = new Date();
        // Image URL which we want to download
        let image_URL = REMOTE_IMAGE_PATH;    
        // Getting the extention of the file
        let ext = getExtention(image_URL);
        ext = '.' + ext[0];
        // Get config and fs from RNFetchBlob
        // config: To pass the downloading related options
        // fs: Directory path where we want our image to download
        const { config, fs } = RNFetchBlob;
        let PictureDir = fs.dirs.PictureDir;
        let options = {
          fileCache: true,
          addAndroidDownloads: {
            // Related to the Android only
            useDownloadManager: true,
            notification: true,
            path:
              PictureDir +
              '/image_' + 
              Math.floor(date.getTime() + date.getSeconds() / 2) +
              ext,
            description: 'Image',
          },
        };
        config(options)
          .fetch('GET', image_URL)
          .then(res => {
            // Showing alert after successful downloading
            console.log('res -> ', JSON.stringify(res));
            // res.base64() 
            // res.path()
            alert('Image Downloaded Successfully.');
          });
      };
    
      const getExtention = filename => {
        // To get the file extension
        return /[.]/.exec(filename) ?
                 /[^.]+$/.exec(filename) : undefined;
      };
    
      return (
        <View style={styles.container}>
          <View style={{ alignItems: 'center' }}>
            <Text style={{ fontSize: 30, textAlign: 'center' }}>
              React Native Image Download Example
            </Text>
            <Text
              style={{
                fontSize: 25,
                marginTop: 20,
                marginBottom: 30,
                textAlign: 'center',
              }}>
              www.aboutreact.com
            </Text>
          </View>
          <Image
            source={{
              uri: REMOTE_IMAGE_PATH,
            }}
            style={{
              width: '100%',
              height: 100,
              resizeMode: 'contain',
              margin: 5
            }}
          />
          <TouchableOpacity
            style={styles.button}
            onPress={checkPermission}>
            <Text style={styles.text}>
              Download Image
            </Text>
          </TouchableOpacity>
        </View>
      );
    };
    
    export default App;
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
      },
      button: {
        width: '80%',
        padding: 10,
        backgroundColor: 'orange',
        margin: 10,
      },
      text: {
        color: '#fff',
        fontSize: 20,
        textAlign: 'center',
        padding: 5,
      },
    });
    

    【讨论】:

    • 是的,我只想离线使用这张图片
    • cool,我怎样才能得到你下载的这个图像并将它加载到Image组件中,或者有没有办法将这个Image转换为Base64字符串并在组件中使用它?
    • 不需要转成Base64。在 res 中,您将拥有可以在 Image 组件中用作 uri 的图像的本地路径。如果我解决了问题,请接受答案
    • 没看懂,能举个例子吗?
    • 我在 fetch 函数中添加了两个示例。两种方式(res.base64()、res.path())都可以在 Image src 道具中使用来显示它)。如果我解决了问题,请接受答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    相关资源
    最近更新 更多