2017-03-24 122 views
-1

我需要創建一個方法將AJAX圖像轉換爲ByteArray並通過AJAX發送到My API PHP。AJAX將圖像轉換爲ByteArray

有人可以幫我嗎?

由於

+0

您需要提供更多的代碼。 – vanloc

+0

我需要像這樣的方法Image x =(Bitmap)((new ImageConverter())。ConvertFrom(jpegByteArray)); –

+0

注:這是在C# –

回答

0

解決方案1:

這是被返回的字節

的Javascript代碼示例:

<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#cmdUpload').click(function() { 
      uploadFile(); 
     }); 

    }); 

    function uploadFile() { 
     var input = document.getElementById('objFile'); 
     // var file = $("#objFile")[0].files[0]; 
     var file = input.files[0]; 
     fr = new FileReader(); 
     fr.onload = receivedText; 
     //fr.readAsText(file); 
     fr.readAsDataURL(file); 
    } 

    function receivedText() { 
     var b64Data = fr.result.split(','); 
     var contentType = 'image/jpeg'; 
     //document.getElementById('editor').appendChild(document.createTextNode(fr.result)) 
     var byteCharacters = atob(b64Data[1]); 
     var byteNumbers = Array.prototype.map.call(byteCharacters, 
             charCodeFromCharacter); 
     var uint8Data = new Uint8Array(byteNumbers); 
     var blob = b64toBlob(b64Data[1], contentType); 
     var blobUrl = URL.createObjectURL(blob); 
    } 

    function charCodeFromCharacter(c) { 
     return c.charCodeAt(0); 
    } 

    function b64toBlob(b64Data, contentType, sliceSize) { 
     contentType = contentType || ''; 
     sliceSize = sliceSize || 1024; 
     var byteCharacters = atob(b64Data); 
     var byteArrays = []; 

     for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { 
      var slice = byteCharacters.slice(offset, offset + sliceSize); 
      var byteNumbers = Array.prototype.map.call(slice, charCodeFromCharacter); 
      var byteArray = new Uint8Array(byteNumbers); 
      byteArrays.push(byteArray); 
     } 
     for (var i = 0; i < byteArray.length; i++) { 
      alert(byteArray[i]); 
     } 

    } 
</script> 

HTML:

<div> 
    <input type="file" id="objFile" size="50" /><br /> 
    <br /> 
    <input type="button" id="cmdUpload" value="Upload" /> 
    <div id="editor"></div> 
</div> 

注:需要jquery庫。

希望它能幫助你。

解決方案2:

參考鏈接:

http://www.macaalay.com/2014/09/26/rendering-images-from-byte-arrays-and-converting-images-to-byte-arrays-using-angularjs/

+0

謝謝這就是我一直在尋找的! –

+0

@LuizFernandoSousaCamargo不客氣! – vanloc