将图片与成二进制大对象(blob)的相互转换

    xiaoxiao2022-06-30  94

    下面分享的是我曾经开发中遇到的问题:将上传的图片或程序生成的图片转换成二进制存入数据库,数据库中保存该图片的字段类型为blob

     

    //这里是将自动生成的图片转换成二进制 BufferedImage image= new BufferedImage(100,100, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.clearRect(0, 0, 100, 100);//创建一个100*100的画布 Color c=new Color(45,204,112);//背景色 g.setColor(c); g.fillRect(0, 0, 100, 100); g.setColor(new Color(255,255,255));//字体颜色 Font font = new Font("宋体", Font.BOLD, 25);//字体、加粗、大小 g.setFont(font); String name= "张三"; //根据name长度自动调整名字在画布中的左右文字 int nameLeng=name.getBytes().length;//名称字节长度 float x_f=(float) (100-(nameLeng*13.5))/2;//X轴偏移量 int x=Math.round(x_f);//偏移量取整 g.drawString(name, x, 60); //重点来了 ByteArrayOutputStream bs =new ByteArrayOutputStream(); ImageOutputStream imOut =ImageIO.createImageOutputStream(bs); ImageIO.write(image,"jpg",imOut); // byte[] b=bs.toByteArray(); Session sessions = getSessionFactory().openSession(); LobHelper lobHelper = sessions.getLobHelper(); Blob blob = lobHelper.createBlob(b); //此方法用于将上传的图片转换成Blob public Blob SetImageToByteArray(String zplj){ FileInputStream is = null; Blob blob = null; Session session = getSessionFactory().openSession(); try { File file = new File(zplj); is = new FileInputStream(file); int streamLength = (int)file.length(); byte[] image = new byte[streamLength]; is.read(image, 0, streamLength);//将字节流转换为byte数组 LobHelper lobHelper = session.getLobHelper(); blob = lobHelper.createBlob(image); } catch (IOException e) { e.printStackTrace(); } finally{ try { //关闭输出流 is.close(); } catch (IOException e) { e.printStackTrace(); }finally { session.close(); } } return blob; } //本页面为getImg.jsp //这里是将二进制转换成图片 Blob blob = ??;//这里的?是从数据库获取的二进制图片 BufferedInputStream inputimage = new BufferedInputStream(blob.getBinaryStream()); try{ BufferedImage image = ImageIO.read(inputimage); OutputStream sos = response.getOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos); encoder.encode(image); inputimage.close(); out.clear(); out = pageContext.pushBody(); }catch(IOException e){ System.out.println(e); } //前台页面使用方法 $("#exit_div").empty().append("<img src='getImg.jsp?ran="+Math.random()+"' />");

     


    最新回复(0)