io流输出图片显示到浏览器,使用json的问题

在试验输出图片显示到浏览器的时候出现了问题。

正确的代码:

@GetMapping("/getImg/{imgname:.+}")
public ResponseEntity getImg(@PathVariable String imgname) {
    Path path = Paths.get("d:\\", imgname);
    Resource resource = resourceLoader.getResource("file:" + path.toString());
    return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(resource);
}

错误的代码:

@RequestMapping(method = RequestMethod.GET, value = "/showImg/{filename:.+}")
public ResponseEntity getFile(@PathVariable String filename) {
    Path path = Paths.get("d:\\", filename);
    Resource resource = resourceLoader.getResource("file:" + path.toString());
     // 都是这句json惹的祸,页面输出不了
     logger.info("resource:{}",JSON.toJSONString(resource));
    return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(resource);
}

这段代码,输出地址后,页面不展示图片。
而且本地的图片也无法查看,而且无法删除,提示java程序正在使用该图片。
比对了变天,发现就多了一句Json.toJSONString()。
这是为什么呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Java输出一个二维码图片,你需要使用第三方库来生成二维码,并将生成的二维码转换为图像格式,在输出输出中。以下是使用ZXing库来生成二维码并输出输出中的示例代码: ```java import java.io.ByteArrayOutputStream; import java.io.OutputStream; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; public class QRCodeGenerator { public static void generateQRCodeImage(String text, int width, int height, OutputStream outputStream) throws WriterException, IOException { // 创建二维码写入器 QRCodeWriter qrCodeWriter = new QRCodeWriter(); // 设置二维码参数 java.util.Map<EncodeHintType, Object> hints = new java.util.HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.MARGIN, 1); // 生成二维码矩阵 BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints); // 转换为图像格式 java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(width, height, java.awt.image.BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? java.awt.Color.BLACK.getRGB() : java.awt.Color.WHITE.getRGB()); } } // 输出输出中 ImageIO.write(image, "png", outputStream); } public static void main(String[] args) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); generateQRCodeImage("https://www.example.com", 200, 200, baos); byte[] imageBytes = baos.toByteArray(); // 将图像字节输出到文件或网络中 // ... } } ``` 在上面的示例代码中,我们使用了ZXing库(可以通过Maven或Gradle等构建工具进行依赖管理)。该代码将生成一个200x200像素的二维码,内容为"https://www.example.com",并将其输出到一个字节数组输出中。最后,你可以将字节数组输出到文件或网络中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值