小结图片操作的一些代码
项目开发中,时常与图片打交道,这里总结一些有用的操作图片的代码。
@author:ZJ 07-2-24
Blog: [url]http://zhangjunhd.blog.51cto.com/[/url]
1.利用servlet在网页上显示本地图片
示例:将本地硬盘d:\temp\1.gif显示在1.html页面上的指定位置。
Showp_w_picpath.java
package com.zj.sample;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@SuppressWarnings("serial")
public class Showp_w_picpath extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
           throws ServletException, IOException {
       try {
           FileInputStream hFile = new FileInputStream("d:\\temp\\1.gif"); // byte流的方式打开文件d:\1.gif
           int i = hFile.available(); // 得到文件大小
           byte data[] = new byte[i];
           hFile.read(data); // 读数据
           hFile.close();
           res.setContentType("p_w_picpath/*"); // 设置返回的文件类型
           OutputStream toClient = res.getOutputStream(); // 得到向客户端输出二进制数据的对象
           toClient.write(data); // 输出数据
           toClient.close();
       } catch (IOException e) {// 错误处理
           PrintWriter toClient = res.getWriter(); // 得到向客户端输出文本的对象
           res.setContentType("text/html;charset=gb2312");
           toClient.write("无法打开图片!");
           toClient.close();
       }
    }
}
 
1.html
在想要显示图片的位置加入此语句:
<img src="showp_w_picpath">
 
web.xml(注册此servlet
<servlet>
    <servlet-name>Showimgservlet-name>
    <servlet-class>com.zj.sample.Showp_w_picpathservlet-class>
servlet>
<servlet-mapping>
    <servlet-name>Showimgservlet-name>
    <url-pattern>/showp_w_picpathurl-pattern>//对应
servlet-mapping>
2.利用JavaScript显示给定网址的图片
javascript
<script>
function change(){
  var str=msgContentImsPicUrl.value;
   document.write('+str+'">'); //对应2.htmlname= msgContentImsPicUrl的文本框
}
script>
 
2.html
<INPUT type=button size=60 value="OK" name=picSubmitUrl
    onclick="change()">
<br>
<input type=text name=msgContentImsPicUrl>
3利用JavaScript实现点击当前图片转换为另一张图片
3.html
(删除"https://blog.51cto.com/viewpic.php?refimg=" +
<img src="http://www.baidu.com/img/logo.gif"
    onclick="this.src='http://www.google.cn/intl/zh-CN/p_w_picpaths/logo_cn.gif'"
    title="点我">
<br>
4.利用JavaScript实现在当前页面显示给定址的图片(网页)
show.js
function pic() {
    var myIframe = document.getElementById("myIframe");//对应4.jsp中的id=myIframeiframe
    var aim = url.value; //对应4.jsp中的name=url的文本框
    myIframe.src = aim;
}
 
4.jsp
<html>
<script src="show.js" type="text/javascript">script>
<body>
    <INPUT maxLength=200 size=30 value=http: // name=url>
    <input type="button" name="Submit" value="ok" onclick="pic()" />
    <br>
    <iframe frameborder="0" style="height: 200px; width: 200px;" src=""
       id="myIframe">iframe>
body>
html>