19

I'm searching into my database a image as a byte array. I want to show this content as file using the markup image, but it doesn't work here.

// Controller which get my image and put into $scope.
function MyController($scope, $http, $location) {  

    var url = '/json/FindImage?id=1';  
    $http.get(url).success(function(result) {  
        $scope.image = result.Image;  
    }  
}  

// HTML
<!-- It doesn't work -->  
<img src="{{image}}" />  
<!-- It doesn't work also -->  
<img ng-src="{{image}}" />  

Any idea? Thank you all!

Kiwanax
  • 1,265
  • 1
  • 22
  • 41

4 Answers4

62

Use ng-src in the following format

<img ng-src="data:image/JPEG;base64,{{image}}">

Don't forget to add a sanitization filter for data to not be marked as unsafe by angular:

$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|blob):|data:image\//);
shA.t
  • 16,580
  • 5
  • 54
  • 111
Assem-Hafez
  • 1,045
  • 10
  • 11
  • GET data:image/PNG;base64,etc.net::ERR_INVALID_URL for me – amdev Aug 05 '16 at 09:34
  • @Assem , even am getting net::ERR_INVALID_URL. What might be the issue. – Hema May 04 '17 at 12:02
  • 1
    @Hema, Yes actually i guess the issue was java side. Now on front side I have and java side I have a ByteArrayOutputStream object which i convert in b64 like that byte[] imageBytes = baos.toByteArray();String b64 = Base64.encodeBase64String(imageBytes);baos.close(); Then put my string in a json. – amdev May 04 '17 at 14:23
  • 1
    Hi @Assem-Hafez, where should the sanitisation filer be added? – Ciaran Gallagher Aug 18 '17 at 21:42
  • 2
    @CiaranGallagher this should go in your config angular.module('myApp').config(['$compileProvider', function($compileProvider) { $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|blob):|data:image\//); } ]); – Assem-Hafez Aug 24 '17 at 01:19
  • Get a image from a function – Lord Darth Vader Oct 05 '17 at 14:17
2

If you can get your server to return the image in a base64 encoded string, you could use a data url as the src attribute.

Anders Ekdahl
  • 22,685
  • 4
  • 70
  • 59
0

Make sure The Data you are returning to show as a image is converted to ToBase64String

In your C# code, Use Convert.ToBase64String(imageBytes) and in the view use this

Amir
  • 105
  • 5
-1

The src attribute of img points to the source file of the image, it doesn't contain the actual source data. You can't do what you want this way; instead, you would have to write an image decoder in JavaScript (e.g., https://github.com/devongovett/png.js), which outputs into a canvas element.

Xophmeister
  • 8,884
  • 4
  • 44
  • 87