2016-06-30 41 views
3

我得到不過從ReactNative CameraRoll的saveImageWithTag功能錯誤。保存本地圖像的東西,如:將React Native中的遠程圖像保存到相機膠捲中?

CameraRoll.saveImageWithTag('./path/to/myimage.png'); 
     .then(res => console.log(res)) 
     .catch(err => console.log(err)); 

給我的錯誤:

Error: The file 「myimage.png」 couldn’t be opened because there is no such file.(…) 

./path/to/myimage.png在這種情況下我會使用到require圖像爲Image源的路徑。本地圖像的完整路徑應該是什麼?我是否需要以不同方式存儲它們才能使它們可訪問?

回答

8

0簡短的回答

使用RNFS找到當地的形象。

1.爲了您的標題「保存遠程圖像在相機膠捲陣營原住民」

的關鍵詞是remote

使用CameraRoll之前,我們應該先link the library

enter image description here

然後,我創建了一個Image和一個Button

render: function() { 
    return (
     <View style={styles.container}> 
      <Image ref="logoImage" 
      style={{ height:50, width: 50 }} 
      source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}} 
      /> 
      <TouchableHighlight style={styles.button} onPress={this._handlePressImage} underlayColor='#99d9f4'> 
      <Text style={styles.buttonText}>Save Image</Text> 
      </TouchableHighlight> 
     </View> 
    ); 
    }, 

當我按下按鈕,程序將保存圖片到相機膠捲:

_handlePressImage: function() { 
    console.log('_handlePressImage.'); 

    var uri = this.refs.logoImage.props.source; 
    console.log(uri); 
    CameraRoll.saveImageWithTag(uri, function(result) { 
     console.log(result); 
    }, function(error) { 
     console.log(error); 
    }); 
    }, 

React Native警告我說的API已被棄用,只是使用promise代替:

var promise = CameraRoll.saveImageWithTag(uri); 
promise.then(function(result) { 
    console.log('save succeeded ' + result); 
}).catch(function(error) { 
    console.log('save failed ' + error); 
}); 

現在,我們可以在我們的相機膠捲中看到徽標圖像。

2.對於你真正的問題在您的內容

儘管你的標題說:remote,代碼使用local路徑。

給出路徑'./path/to/myimage.png',我假設圖像路徑是相對於.js文件。也就是說,您的圖像與最終運行的應用程序無關,因此無法找到圖像文件。

現在改變Image使用本地文件:

<Image ref="logoImage" 
    style={{ height:50, width: 50 }} 
    source={require('./logo_og.png')} 
/> 

和保存這樣的形象:

var promise = CameraRoll.saveImageWithTag('./logo_og.png'); 

導致:

enter image description here

因爲CameraRoll API是對應於Native Component,它屬於最終運行的應用程序,而不是javascript。

3.使用RNFS保存本地圖片

首先運行以下命令:

npm install react-native-fs --save 

,然後鏈接庫。

Library/Caches下把圖像後:

enter image description here

我們可以保存在本地圖像:

var cacheImagePath = RNFS.CachesDirectoryPath+"/logo_og.png"; 
console.log(cacheImagePath); 
var promise = CameraRoll.saveImageWithTag(cacheImagePath); 
promise.then(function(result) { 
    console.log('save succeeded ' + result); 
}).catch(function(error) { 
    console.log('save failed ' + error); 
}); 

enter image description here

感謝。

+0

很好的回答。謝謝!是的,我發現我可以使用遠程URL但忘記更改問題標題。儘管如此,仍在苦苦掙扎着本地文件。我會看看react-native-fs。你使用CachesDirectory而不是DocumentDirectory的任何原因? – nicholas

+0

@nicholas CachesDirectory或DocumentDirectory只是一個例子:) –

+0

謝謝!後續問題:保存動畫gif僅保存iOS上的第一幀。照片應用通常不會在任何情況下顯示動畫,但即使在發送電子郵件或以其他方式分享gif並將其打開後,它似乎只是一個靜態gif ...關於發生了什麼的任何想法? – nicholas

相關問題