Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert octet-stream to image

I need to fetch a file using a $http.get. The data returns as application/octet-stream But i know this file is an image.

How can i display this file as an image?

I tried

var nuroImage = new Image();
nuroImage.onload = function {
  scope.imageSrc = this.src;
}

$http(req).then(
  funciton(response) {
    nuroImage.src = "data:application/octet-stream," + response.data
  }

I get 200ok but the image isn't showing

Is it possible to transform octet-stream to jpeg/png?

like image 569
doron Avatar asked May 29 '16 14:05

doron


2 Answers

You can use fetch() to request image as Blob, URL.createObjectURL() to create a blob URL from response

(async () => {
  const res = await fetch('https://httpbin.org/image/png')
  const blob = await res.blob()
  const img = new Image()
  img.src = URL.createObjectURL(blob)

  // newer promise based version of img.onload
  await img.decode()
  
  document.body.append(img)

  // Don't forget to revoke the blob url when 
  // you no longer need it (to release memory)
  URL.revokeObjectURL(img.src)
})()
like image 134
guest271314 Avatar answered Sep 17 '22 18:09

guest271314


I guess you should something like this:

  • Use atob to encode the resulting run-length compressed image file
  • And use <img src="data:image/png;base64,...."> to include that into the html5 file

If your file is not PNG, do add corresponding mime type.

Sample:

<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/
f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67
QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g7
7ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7"/>
  • https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/atob
  • http://www.html5rocks.com/en/tutorials/canvas/integrating/
like image 20
gevorg Avatar answered Sep 20 '22 18:09

gevorg