react-native

react native 生成二维码并保存

2023-09-21  本文已影响0人  王宣成
import QRCode from 'react-native-qrcode-svg';
import * as MediaLibrary from 'expo-media-library';
import * as FileSystem from 'expo-file-system';
    let myQRCode = useRef();
    const saveQRCodeToBase64 = () => {
        myQRCode.toDataURL((data) => {
            // console.log(data); // 输出二维码的base64字符串
            // 你可以在此方法内部将base64编码的数据保存为图片
            saveQRToDiskAsync(data)
        });
    };

    async function saveQRToDiskAsync(qrCodeBase64) {
        if (Platform.OS === 'android') {
            const { status } = await MediaLibrary.requestPermissionsAsync();

            if (status !== 'granted') {
                alert('需要存储权限才能保存二维码');
                return;
            }
        }

        let filePath = FileSystem.documentDirectory + 'qrcode.png';
        await FileSystem.writeAsStringAsync(filePath, qrCodeBase64.replace('data:image/png;base64,', ''), {
            encoding: FileSystem.EncodingType.Base64
        });

        const asset = await MediaLibrary.createAssetAsync(filePath);
        await MediaLibrary.createAlbumAsync('QR Codes', asset, false)
            .then(() => {
                alert('二维码已保存!');
            })
            .catch(error => {
                alert('保存二维码出错,错误为: ' + error.message);
            });
    }
                     <View style={styles.qrCodeContainer}>
                          <View style={{ padding: 5 }}>
                                <QRCode
                                    value={qrCodeValue}
                                    size={100}
                                    color="black"
                                    backgroundColor="white"
                                    getRef={(c) => (myQRCode = c)}
                                />
                            </View>
                            <TouchableOpacity onPress={saveQRCodeToBase64}>
                                <Text style={styles.clickSaveText}>{t('clickSave')}</Text>
                            </TouchableOpacity>
                        </View>
上一篇 下一篇

猜你喜欢

热点阅读