【问题标题】:Image is not getting displayed from byte array in java图像未从 java 中的字节数组中显示
【发布时间】:2014-08-04 11:15:36
【问题描述】:

我有两个疑问:
1.当我试图打印我从java获取到客户端的字节数组时,我得到了奇怪的值类型。我不确定它是字节数组还是像素数据。如果不是字节数组,则需要进行什么更正。代码参考粘贴在下面
2.目前我正在从数据库中读取图像并写入服务器端的一个字节数组,我正在将此字节数组添加到json对象中并发送。但是图像没有显示请参见下面的代码:

//this line will fetch the image data from db and i am storing into byte array
     byte[] imageData = smpResource.getValue();

//i am adding this byte array into json object and sending.
    JSONObject result = new JSONObject();
    result.put("image", imageData);

//Client side code looks like:

var temp = null;
var jqxhr = jQuery.post(
            '$link.getContextPath()/setEmployee.do',
            {
                empID: getSelectedEmpID(), empName: getSelectedEmpName()
            },
            function (data) {
            jQuery.each(data, function(field, value){
                // here in value i will be getting that byte array and i am storing in  the below img src
                if( "image" == field ) {
                    temp = value;
                    // please check the attachments and please confirm whether it was printing byte array or pixel data
                    alert("temp" + temp);
                }
            });

          selectedImage.innerHTML = "<img src='data:image/jpg;base64, temp'/>";
            ,
            "json"
        ).error( function(){
            // if there was an error, select the parent...
            selectedTreeNode.remove();
        });
    }

让你理解 Guyz 可能有点复杂,但我已尽力而为。但请告诉我,我会尝试其他方式。

【问题讨论】:

  • 在您分配 innerHTML 的地方,您只需在字符串文字中使用“temp”。您需要连接变量,即 selectedImage.innerHTML = "";
  • @WouterLievens——我也尝试过这种方式,但没有显示静止图像..想知道我添加的快照是字节数组格式还是其他格式..我没有得到正是

标签: java javascript html json image


【解决方案1】:

要在带有 data/base64 url​​ 的图像中显示,您需要将其编码为 Base64 格式(请参阅http://en.wikipedia.org/wiki/Base64)。您可以修改后端以将图像写入 base64 格式(请参阅Java BufferedImage to PNG format Base64 String),作为字符串而不是数组。对于 JSON,它也更加紧凑!

【讨论】:

  • :--感谢您的指导,但静止图像未显示。添加 byte[] imageData = smpResource.getValue();字符串 enocdeString = Base64.encodeBase64URLSafeString(imageData);并且在 json 对象中也发生了变化,例如 result.put("image", enocdeString);现在我可以看到客户端正确的字节数组格式即将到来,但我仍然可以看到图像为空
  • 首先尝试手动创建 HTML 并手动复制您生成的 base64 字符串,以验证它是否编码正确。
  • @Wouter-- 也通过复制粘贴手动尝试,但我仍然可以看到没有显示图像
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 2021-04-12
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多