2016-01-20 113 views
14

我正在構建一個反應本機應用程序,需要以base64字符串格式存儲圖像以便進行脫機查看功能。React-Native:將圖像url轉換爲base64字符串

什麼庫/函數會給我最好的結果來存儲圖像作爲base64字符串?假設我的網址是「http://www.example.com/image.png」。

此外,我需要做出http請求才能將它存儲爲字符串之前?我的邏輯說是的,但在原生反應中,您可以將圖像加載到Image>組件上,而無需先從服務器請求它們。

什麼是最好的選擇做到這一點在反應原生?

回答

10

我用react-native-fetch-blob,基本上它提供了大量的文件系統和網絡功能,使數據傳輸很容易。

import RNFetchBlob from 'react-native-fetch-blob' 

const fs = RNFetchBlob.fs 

let imagePath = null 

    RNFetchBlob 
      .config({ 
       fileCache : true 
      }) 
      .fetch('GET', 'http://www.example.com/image.png') 
      // the image is now dowloaded to device's storage 
      .then((resp) => { 
       // the image path you can use it directly with Image component 
       imagePath = resp.path() 
       return resp.readFile('base64') 
      }) 
      .then((base64Data) => { 
       // here's base64 encoded image 
       console.log(base64Data) 
       // remove the file from storage 
       return fs.unlink(imagePath) 
      }) 

Project Wiki

+1

如何使用像 '用戶名/項目/ example.png' 地方形象? – Sathya

3

爲了圖像轉換爲base64在本地做出反應,在實用的FileReader是有幫助的:

const fileReader = new FileReader(); 
fileReader.onload = fileLoadedEvent => { 
    const base64Image = fileLoadedEvent.target.result; 
}; 
fileReader.readAsDataURL(imagepath); 

這需要react-native-file

另一種替代方案,也許是首選的替代方案是使用NativeModules。 Medium article顯示如何。它需要創建一個native module

NativeModules.ReadImageData.readImage(path, (base64Image) => { 
    // Do something here. 
}); 
4
ImageEditor.cropImage(imageUrl, imageSize, (imageURI) => { 
     ImageStore.getBase64ForTag(imageURI, (base64Data) => { 
      // base64Data contains the base64string of the image 
     }, (reason) => console.error(reason)); 
}, (reason) => console.error(reason)); 
相關問題