从数据库中读取并生成图片的Servlet(转)

大体思路
1)创建ServletOutputStream对象out,用于以字节流的方式输出图像
2)查询数据库,用getBinaryStream方法返回InputStream对象in
3)创建byte数组用作缓冲,将in读入buf[],再由out输出

注:下面的例程中数据库连接用了ConnectionPool,以及参数的获得进行了预处理

package net.seasky.music;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import net.seasky.util.*;
import net.seasky.database.DbConnectionManager;

public class CoverServlet extends HttpServlet {
private static final String CONTENT_TYPE = "image/gif";
public void init(ServletConfig config) throws ServletException {
super.init(config);
}

public void doGet(HttpServletRequest request, HttpServletResponse response
) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
int albumID;
ServletOutputStream out = response.getOutputStream();
try {
albumID = ParamManager.getIntParameter(request,"albumID",0);
}
catch (Exception e) {
response.sendRedirect("../ErroePage.jsp");
return;
}
try {
InputStream in=this.getCover(albumID);
int len;
byte buf[]=new byte[1024];
while ((len=in.read(buf,0,1024))!=-1) {
out.write(buf,0,len);
}
}
catch (IOException ioe) {
ioe.printStackTrace() ;
}
}

private InputStream getCover(int albumID) {
InputStream in=null;
Connection cn = null;
PreparedStatement pst = null;
try {
cn=DbConnectionManager.getConnection();
cn.setCatalog("music");
pst=cn.prepareStatement("SELECT img FROM cover where ID =?");
pst.setInt(1,albumID);
ResultSet rs=pst.executeQuery();
rs.next() ;
in=rs.getBinaryStream("img");
}
catch (SQLException sqle) {
System.err.println("Error in CoverServlet : getCover()-" + sqle);
sqle.printStackTrace() ;
}
finally {
try {
pst.close() ;
cn.close() ;
}
catch (Exception e) {
e.printStackTrace();
}
}
return in;
}

public void destroy() {
}
}  [@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/9650775/viewspace-924265/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/9650775/viewspace-924265/

可以使用zxing库生成二维码,再将二维码图片化为字节数组,存入数据库。 下面给出一个简单的示例代码: 1. 添加依赖 在pom.xml添加以下依赖: ```xml <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.4.0</version> </dependency> ``` 2. 编写生成二维码的方法 ```java public static byte[] generateQRCode(String content) throws WriterException, IOException { int width = 200; // 二维码图片宽度 int height = 200; // 二维码图片高度 // 设置二维码参数 Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.MARGIN, 1); // 生成二维码 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); // 将BitMatrix换为BufferedImage BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix); // 将BufferedImage换为字节数组 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(image, "png", outputStream); byte[] bytes = outputStream.toByteArray(); return bytes; } ``` 3. 在Controller调用方法并保存到数据库 ```java @Controller public class QRCodeController { @Autowired private QRCodeService qrCodeService; @RequestMapping("/generateQRCode") public String generateQRCode(Model model, @RequestParam String content) { try { byte[] bytes = QRCodeUtil.generateQRCode(content); qrCodeService.saveQRCode(bytes); } catch (Exception e) { e.printStackTrace(); } return "success"; } } ``` ```java @Service public class QRCodeServiceImpl implements QRCodeService { @Autowired private QRCodeMapper qrCodeMapper; @Override public void saveQRCode(byte[] bytes) { QRCode qrCode = new QRCode(); qrCode.setBytes(bytes); qrCodeMapper.insert(qrCode); } } ``` 4. 在页面显示二维码 在页面使用img标签,并将src属性设置为一个servlet或controller的路径,通过读取数据库的二维码字节数组生成二维码图片并显示。 ```html <img src="${pageContext.request.contextPath}/showQRCode?id=${qrCode.id}"> ``` ```java @Controller public class QRCodeController { @Autowired private QRCodeService qrCodeService; @GetMapping("/showQRCode") public void showQRCode(HttpServletRequest request, HttpServletResponse response, Long id) { try { QRCode qrCode = qrCodeService.getQRCodeById(id); byte[] bytes = qrCode.getBytes(); response.setContentType("image/png"); ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(bytes); outputStream.flush(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` ```java public interface QRCodeMapper { void insert(QRCode qrCode); QRCode selectById(Long id); } ``` ```java public class QRCode { private Long id; private byte[] bytes; // getter/setter方法 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值