Display PNG image using AngularJS after converting hexadecimal string to Blob

I have a web page using angularjs 1.4.8 where I am attempting to display an image obtained from a GET url request.

Below is the code snippet from my page:

<div ng-show="message.message == null && message.is_image != null">
    <a href="#" ng-click="downloadFile(message.id_message)">
      <img data-ng-src="data:image/{{message.image_resolution}};base64,{{message.image_preview}}"/>
    </a>
</div>

The JSON data from Cassandra DB looks like this:

created_date:"2017-03-31 22:05:42.284Z"
id_message:"e6e2a5cb-ec25-472f-a59b-3f16a3a8afa9"
id_user_link:"47ed65bf-5520-4901-88c8-01980ffbcd4d"
id_user_sent:"3495c2de-c93c-4323-8e48-1fcecbfde625"
image_length:174443
image_name:"5.png"
image_preview:"0x89504e470d0a1a0a0000000d49484452000007800000039a080600000079a04f28000038714944415478daecd9496e55570045d13bfff124d442c654016320c4d4219832046308a132087199c26ba4f1fed65ad29ec0e99e71ec97635392244992244992244992b4f90d23489224499
...
... some other 90 lines of symbols
...
00000108401d8006c0096244906600000000008c2006c0036004b922403300000000004610036001b802549920118000000008230001b800dc09224c9000c000000004118800dc00660499264000600000080200cc0066003b024493200030000004010066003b001589224198001000000200803b001d8002c49920cc000000000108401d8006c0096244906600000000008c2006c0036004b92a4ff95fe0ffc7d46dd1b63a2b10000000049454e44ae426082"
image_resolution:"png"
is_image:1
message:null

Unfortunately, the images are not displaying on the webpage, only broken links: https://i.sstatic.net/u7R0m.png I have tried looking into various solutions suggested by others:

Angularjs showing image blob

Display blob image in html with angularjs

AngularJS - Show byte array content as image

However, none of these solutions seem to work for me. I even attempted variations of the code snippet provided earlier:

<img data-ng-src="data:image/{{message.image_resolution}};base64,{{b64encoded(message.image_preview)}}"/>

Accompanied by the following JavaScript function:

 $scope.b64encoded = function(image_preview){
        //btoa(String.fromCharCode.apply(null, response.data[0].ClassImage.data));
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|blob):|data:image_preview\//);    
        return btoa(String.fromCharCode.apply(null, image_preview));
    }

UPDATE After extensive troubleshooting, it turns out the issue was not with AngularJS or blobs but actually a Java problem:

byte[] previewSizeByte = baos.toByteArray();
. As a result, I ended up converting this to a text field, and modified my Java code to use BufferedImage for previews:
String base64String = imgToBase64String(preview, fileFormat);

This change led me to update the Java method as follows:

private String imgToBase64String(BufferedImage preview, String fileFormat) {
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        ImageIO.write(preview, fileFormat, Base64.getEncoder().wrap(os));
        return os.toString(StandardCharsets.ISO_8859_1.name());
    } catch (final IOException ioe) {
        throw new UncheckedIOException(ioe);
    }
}

I would like to express my gratitude to the members of Stack Overflow for their valuable insights and assistance throughout this troubleshooting process.

Answer №1

It seems that CassandraDB is transmitting the image data in a hexadecimal format. It might be more efficient to send it as a base64 string, which would also simplify its usage.

Below is a function that can convert a hexadecimal string into an image/png Blob and then display the image:

angular.module("myApp",[]).controller("myVm", function($scope) {
  var vm = $scope;

  var testHex = 
    ["0x89504e470d0a1a0a0000000d494844520000003c00000028040300000050",
       "9584cc0000001b504c5445000000ffffff1f1f1f7f7f7f3f3f3f9f9f9f5f",
       "5f5fdfdfdfbfbfbf2cb790f6000000097048597300000ec400000ec40195",
       "2b0e1b000000b749444154388ded90cf0a83300cc63faaf5394a5defc56c",
       "ee2a0c760e2a3b0b6e3ec7c0175f5aff1e77da657ea40dcd2ff90a010efd",
       "9772a2f3f6ea4b830e121915b1a04e859999066a4b1801562dec544c3d36",
       "cc723506ac9791809538f564af54055c33f8861d76d0cacfd30efc9450c3",
       "b0e20189e28847aac5397458b7e2175d4cde4ed37252cff7d83ce367c849",
       "b56014ecf638fa28bf62cd49b7c3e9a384f86764269cbde5bf665b969230",
       "31adb25feffdd02ff50109f91bbd7897f34a0000000049454e44ae426082"]
    .join('');

  vm.hex = testHex;        
  vm.imgUrl = URL.createObjectURL(toPngBlob(testHex));
  
  function toPngBlob(str){
    var hexStr = str.slice(2);
    var buf = new ArrayBuffer(hexStr.length/2);
    var byteBuf = new Uint8Array(buf);
    for (let i=0; i<hexStr.length; i+=2) {
      byteBuf[i/2] = parseInt(hexStr.slice(i,i+2),16);
    }
    var blob = new Blob([byteBuf], {type: "image/png"});
    return blob;
  };
  
});
<script src="//unpkg.com/angular/angular.js"></script>

  <body ng-app="myApp" ng-controller="myVm">
    <h1>Convert hex string to PNG Blob</h1>
    {{hex}}<br>
    {{imgUrl}}<br>
    <img ng-src="{{imgUrl}}">
    
  </body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

steps to invoke a class within a function

I'm currently attempting to invoke a model class from the Axios response. Instead of displaying an alert, I would like to show a modal popup. Can someone assist me with how to call the modal class from the Axios interceptor function? Thank you in adva ...

Node.js error: Headers cannot be set once they have been sent

I'm struggling with sending form data through express.js and encountering the following error: After establishing communication, it's not possible to modify headers. This is the current state of my code: app.post('/api/users/profile/:us ...

Jstree's select_node function is failing to trigger

I am having an issue with the select_node.jstree function not firing properly. Below is the code snippet: $(document).ready(function () { //$("#MySplitter").splitter(); setupSplitter(); $("#divJsTreeDemo").jstree({ "themes": { "theme": "d ...

Pause rendering of Three.js when the video texture needs to be updated

I attempted to apply a video as a texture on a mesh, and tried two different examples: and Both examples worked fine online but didn't display anything when downloaded from GitHub. When I added the code: videoTexture.needsUpdate = false; the floo ...

How can I retrieve the position of a div or an image within a div (specifically the top and left coordinates) and incorporate these values into CSS?

I'm currently working on a website that is dynamic and utilizes bootstrap. I am looking to incorporate an animation where the dynamic thumbnails in the col-md-4 div zoom to 100% when clicked, appearing at the center of the container. I am struggling ...

Issue with data transfer in Angular 6 routes

I created an application that showcases a table of different cars: Here is my code snippet for the car component: Carcomponent.html <tbody> <tr *ngFor="let car of allCars; index as carId" \> <td [routerLink]="[&apos ...

The parent view in AngularJs navbar should remain active when any child view is currently active

My goal is to have the first view based on some sub-views while the main view remains abstract and only redirects to the first sub-view. I have implemented two nav bars for navigation - one for normal views and another specifically for navigating within th ...

Making asynchronous requests using AJAX

$.ajax({ async:false, url: "ajax/stop_billed_reservation_delete.php", type: "POST", dataType : "json", data : { "rid" : <?php echo $_GET['reservationId']; ?> }, success: function(result){ ...

Node's getRandomValues() function is throwing an "expected Uint8Array" error

Currently, I am experimenting with the getRandomValues() function to enhance an encryption REST API that I am developing for practice. My server is using Node, which means I do not have access to a window object containing the crypto object normally housin ...

Using Three.JS to implement raycasting on a custom mesh

I've been tackling an issue with raycasting a custom mesh in three.js. Surprisingly, while raycasting works flawlessly on some imported meshes, it just doesn't seem to cooperate at all with my custom mesh. After extensive research, I came across ...

Retain the previously selected option in a PHP combobox even when changing pages

Can someone please assist me with my PHP code? I am having trouble keeping my combobox unchanged after a page reload. It works fine until I change pages in my pagination. Can anyone help? THIS IS MY PHP. PHP ...

Revealing or Concealing a column with a Checkbox Toggle

Showing and Hiding Columns with Checkbox Selection DISCLAIMER: I have exhausted all available solutions before posting this question, as none of them have worked for me so far. I joined specifically because the existing solutions did not meet my needs. T ...

Creating an object in JavaScript using an array type初始化数组类型为对象javascript

In my code, there is an interface defined as Products export interface Products{ category: string; imageUrl: string; price: number; title: string; } Within my component, I have a variable named products which is an array of type Product ...

Spotlight barn doors in Three.js are an innovative feature that

I have been experimenting with three.js to build a scene featuring spotlights. Is there a way to achieve the barn door effect for the lights in three.js? I attempted using small cubes as barn doors to block the light, but it was not successful. I am look ...

Adding a node to a JSTree at a precise location within the tree

I'm currently working on updating a JSTree structure whenever the open_node.jstree event is triggered. The goal is to populate the children of the parent node that has been opened. treeContent.jstree({ "json_data": {"data": jsonData}, ...

The validation function is always one step ahead of React component props

I have developed a validation function that checks user input for errors as they type. Additionally, I have implemented an <Input/> component and included an error message <div>. My goal is to provide a string to the "message" prop on the <I ...

Several directories for viewing in Node.js with Express

I have been researching different solutions, but I am still unsure about how to effectively integrate Express with multiple view folders. Imagine an Express application divided into distinct parts, each organized in its own subfolder: app +partA + ...

What steps can be taken to fix a syntax error in a NodeJS express server code?

I am currently facing a syntax error in the code below, and I'm struggling to fix it. The specific error message is as follows: node staticapi.js /Users/v/Desktop/CS-Extra/EIP/A5/staticapi.js:123 res.status(200).send("Api is running") ...

It appears that the Angular 2 HTTP header is being produced or transmitted erroneously

Trying to send a request to my backend that uses HTTP Basic authentication for testing purposes. username: user password: password The correct header should be: Authorization: Basic dXNlcjpwYXNzd29yZA== Request tested with this header in Chrome Advance ...

Show an xeditable form that can be edited within a popup window

Looking for a way to enclose the editable form within a bootstrap uib-popover-template. Tried the editable ui-bootstrap popover method, but encountering unexpected issues. Check out Plunker 1 --> https://plnkr.co/edit/vXeVoFYVU2IU08CF Issue with angul ...