Cornerstone加载base64表示的jpg图像

cornerstone文档https://docs.cornerstonejs.org/

cornerstone的给的样例代码是直接解析XHR链接,但很多时候手头的数据只是base64编码,网上没找到解答,自己搞了一下。

import * as cornerstone from 'cornerstone-core'
import * as cornerstoneWebImageLoader from 'cornerstone-web-image-loader'

cornerstoneWebImageLoader.external.cornerstone = cornerstone;

前提:图像相关信息在this.$store.state.singleImage中,其中base64编码信息在this.$store.state.singleImage.imgdata

loadImageData()调用getExampleImage()


getExampleImage(imageId) {
  var that = this;
  var width = 256;
  var height = 256;

  var img = document.createElement("img");
  img.src = that.$store.state.singleImage.imgdata;
  // 使用Image对象获取图像长和宽,并准备转化为canvas对象
  width = img.width;
  height = img.height;

  var canvas = document.createElement("canvas");
  function loadPixelData () {
    console.log('$store.state.singleImage.imgdata', that.$store.state.singleImage.imgdata.length);
    console.log('getExampleImage.loadPixelData',img.width, img.height);

    // 用canvas获取图像数据的像素矩阵(数组)
    canvas.width = img.width;
    canvas.height = img.height;
    canvas.getContext("2d").drawImage(img, 0, 0);
    var pixelData_obj = canvas.getContext("2d").getImageData(0,0,canvas.width,canvas.height);    // 获取画布上的图像像素矩阵
    var pixelData = pixelData_obj.data;

    return pixelData;
  }

  var image = {
    imageId: imageId,
    minPixelValue : 0,
    maxPixelValue : 255,
    slope: 1.0,
    intercept: 0,
    windowCenter : 127,
    windowWidth : 256,
    getPixelData: loadPixelData,	// 要求图像的像素矩阵
    rows: height,
    columns: width,
    height: height,
    width: width,
    color: true,	// 注意:为彩色图像
    rgba: true,		// 注意:使用rgba表示(canvas直接导出)
    columnPixelSpacing: .8984375,
    rowPixelSpacing: .8984375,
    sizeInBytes: width * height * 4
  };

  return {
    promise: new Promise((resolve) => {
      resolve(image);
    }),
    cancelFn: undefined
  };
},

loadImageData(){
  // TODO: 图片切换时会发生偏移,待解决
  let element = document.getElementById('dicomimage');
  // console.log('element:', element)

  cornerstone.enable(element);
  // register our imageLoader plugin with cornerstone
  cornerstone.registerImageLoader('example', this.getExampleImage);

  cornerstone.loadImage('example://' + this.$store.state.singleImage.imgname).then(function(image) {
    cornerstone.displayImage(element, image);
  });

},

注意imagegetPixelData参数,顾名思义,可以检查一下该数组长度一定是图像大小的倍数。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐