前端Web界面,显示Java后端的图片流

十点数据 1年前 ⋅ 2842 阅读

最近在做一个寺庙相关信息的大屏显示系统时,由于使用的历史系统后台,跨域问题较难解决,最后决定使用图片流的方式,在前端显示图片。 图片.jpg

后端Java如下:

@RequestMapping(value = "/getFileStream", method = RequestMethod.GET)
public void pdfStreamHandler(HttpServletRequest request,
		HttpServletResponse response) {
	String templeId = request.getParameter("templeId");// 寺庙ID
	String propName[] = new String[] { "fileSubordinateId", "fileFrom" };
	Object propValue[] = new Object[] { Long.parseLong(templeId), 1 };
	List<TempleFile> tfList = templeFileService.queryByProerties(propName,
			propValue);
	String fileSrc = null;
	if (StringUtils.isNotBlank(tfList)) {
		for (TempleFile tf : tfList) {
			if (tf.getFileType().intValue() == 1) {
				fileSrc = tf.getFileSavePath();
				break;
			}
		}
	}
	try {
		File pf = new File(fileSrc);
		if (!pf.exists()) {
			return;
		}
		double rate = 1; // rate是压缩比率 1为原图 0.1为最模糊
		int[] results = getImgWidth(pf);
		int widthdist = 0;
		int heightdist = 0;
		if (results == null || results[0] == 0 || results[1] == 0) {
			return;
		} else {
			widthdist = (int) (results[0] * rate);
			heightdist = (int) (results[1] * rate);
		}
		Image src = javax.imageio.ImageIO.read(pf);
		BufferedImage tag = new BufferedImage((int) widthdist,
				(int) heightdist, BufferedImage.TYPE_INT_RGB);

		tag.getGraphics().drawImage(
				src.getScaledInstance(widthdist, heightdist,
						Image.SCALE_SMOOTH), 0, 0, null);
		ServletOutputStream fout = response.getOutputStream();
		ImageIO.write(tag, "jpg", fout);
		fout.close();
	} catch (Exception e) {
		// 异常处理
	}
}

private static int[] getImgWidth(File file) {
	InputStream is = null;
	BufferedImage src = null;
	int result[] = { 0, 0 };
	try {
		is = new FileInputStream(file);
		src = javax.imageio.ImageIO.read(is);
		result[0] = src.getWidth(null); // 源图宽
		result[1] = src.getHeight(null); // 源图高
		is.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return result;
}

前端代码如下:

<img id="picture" src= "http://XX.XX.XX.XX/sms/bigscree/getFileStream?templeId=15"  style="width: 375px;height: 166px;vertical-align: middle; text-align: center;" />';

最后显示如下所示:

QQ截图20200504151314.jpg

相关阅读:

Controller注解@CrossOrigin,解决跨域问题

前端Web界面播放Java后端返回的音频流,视频流

全部评论: 0

    我有话说: