0
我想要在文件系統設備上保存圖像。該圖像是從couchdb服務器獲取的。 來自couchdb服務器的響應是MIME。 我解析了MIME字符串,並獲得了圖像數據。這是代碼:保存圖像從電話應用程序中的couchdb服務器獲取
function getImg(){
$.ajax({
url: "http://localhost:5984/testdb/10ef83b61f50e210cfe82620ef0016a3?attachments=true",
success: function(data){
var split = data.split("\r\n\r\n");
var imageData = split[2].split("\r\n--")[0];
var jsonData = split[1].split("\r\n--")[0];
var jsonObj = JSON.parse(jsonData);
//imageData is a string that contain image/jpeg read from MIME response
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem){
fileSystem.root.getDirectory("PhoneGap Example", {create: true}, function(parent){
console.log("Directory create/open");
var d = new Date();
var n = d.getTime();
//new file name
var newFileName = n + ".jpeg";
fileSystem.root.getFile(newFileName, {create: true}, function(fileEntry){
console.log("create file image: " + fileEntry.name);
fileEntry.createWriter(function (writer){
writer.onwrite = function (evt){
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
largeImage.src = writer.fileName;
};
writer.write(imageData);
}, onWriterError);
fileEntry.moveTo(parent, newFileName, function(newFileEntry){
console.log("file move: " + newFileEntry.name);
}, onMoveFileError);
}, onResolveError);
}, onGetDirectoryFail);
}, onFileSystemError);
}
});
}
該文件被正確保存,但文件的內容不是圖像。 我認爲,因爲我在文件中寫入的imageData是一個字符串而不是二進制數據。 我嘗試字符串轉換爲二進制數據與功能:
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
,但我有同樣的問題。 如何正確保存圖像?
no。數據不是base64編碼的。我收到了MIME中的回覆,目的是不使用base64。 imageData是一個字符串轉換二進制數據。我讀了phonegap文檔,但我不知道如何extrat數據二進制字符串imageData – Morris
在我提到的示例中有一行「dataView = new Int8Array(data);」然後一個循環將dataView的每個元素寫入文件,我認爲這可能是有用的,你試圖達到什麼... – QuickFix