java.io.filenotfoundexception: the system cannot find the file specified

記錄一個成功例子。

在Java EE項目下,想讀取圖片,就遇到了這個問題。

問題描述:讀取圖片並轉化爲byte數組。

然後百度、谷歌了一遍又一遍,最終找到了思路解決了問題。

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		
		final float FACTOR  = 4f;
		<span style="font-size:14px;"><strong>BufferedImage img = ImageIO.read(new FileInputStream(
				this.httpRequest.getSession()
                                .getServletContext().getRealPath("/") + 
                               "/images/ic_launcher.png"));</strong></span>
		int scaleX = (int) (img.getWidth() * FACTOR);
		int scaleY = (int) (img.getHeight() * FACTOR);
		Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
		BufferedImage buffered = new BufferedImage(scaleX, scaleY, BufferedImage.TYPE_INT_RGB);
		buffered.getGraphics().drawImage(image, 0, 0 , null);
		
		ImageIO.write(buffered, "png", out);
                //這個Action類實現了ServletResponseAware接口
                //需要setHeader()才能成功輸出圖片
                this.httpResponse.setHeader("content-type", "image/jpeg");
                this.httpResponse.getOutputStream().write(b);

圖片在項目中的存放位置:


發佈了20 篇原創文章 · 獲贊 1 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章