`

图片中格式的互转

阅读更多
public class ImageUtil {
	/**
	 * 将图片转换成Base64
	 * @param imgFilePath
	 * @return
	 */
	private double scaleWidth = 358.0;

    private double scaleHeight = 441.0;
    
    private InputStream fis = null;
    
    private BufferedImage bi;
    
    public static String GetImageStr(String imgFilePath) {
         // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
         byte[] data = null;
         // 读取图片字节数组
         try {
             InputStream in = new FileInputStream(imgFilePath);
          data = new byte[in.available()];
          in.read(data);
          in.close();
         } catch (IOException e) {
          e.printStackTrace();
         }
         // 对字节数组Base64编码
         BASE64Encoder encoder = new BASE64Encoder();
         return encoder.encode(data);// 返回Base64编码过的字节数组字符串
        }
    

    /**
     * 本地图片转成InputStream流对象。需要一个参数,base64编码的字符串,可由步骤一得到。
     * @param base64string
     * @return
     */
        public static InputStream BaseToInputStream(String base64string) {
    		ByteArrayInputStream stream = null;
    		try {

    			BASE64Decoder decoder = new BASE64Decoder();

    			byte[] bytes1 = decoder.decodeBuffer(base64string);

    			stream = new ByteArrayInputStream(bytes1);

    		} catch (Exception e) {
    			// TODO: handle exception
    		}
    		return stream;
    	} 
        /**
         * 根据个人编号查询照片,并转换成BASE64。
         * @param base64string
         * @return
         * @throws AppException 
         */
        
        public String queryPhoto(String aac001) throws AppException 
        {
        	InputStream inputStream = null;
            BufferedInputStream bis = null;
            try
            {
                if ("".equals(aac001) || aac001 == null)
                {
                	return "-1$个人编号有误。$$";
                } else
                {
                	HashMap primaryKeys = new HashMap();
            		primaryKeys.put("CC_AC30.CC_AAC001", aac001);
            		String fullColumnName = "CC_AC30.BAC200";	
            		inputStream = SqlUtil.getInstance().executeBlobQuery(fullColumnName, primaryKeys);
                    if (inputStream == null)
                    {
                    	return "-1$系统中没有该人员照片信息!$$";
                    }
                }

            } catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return "-1$查询照片异常。$$";
            } finally
            {
                try
                {
                    if (bis != null)
                        bis.close();
                    if (inputStream != null)
                        inputStream.close();
                } catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
            Map map = photoToBase64(inputStream);
            Object picbase64=map.get("picbase64");
            return picbase64.toString();
        }  
        
      //照片转格式
        private Map photoToBase64(InputStream inputStream) throws AppException
        {
            BufferedInputStream bis = null;
            Map map = new HashMap();
            byte[] photo = null;
            String base64Str = null;
            ByteBuffer sb = null;

            //对图片进行base64编码
            try
            {
                sb = ByteBuffer.allocate(inputStream.available());
                int buffersize = 1024;
                photo = new byte[buffersize]; // 缓存
                int bytesRead = 0; // 读取数据临时变量
                bis = new BufferedInputStream(inputStream);

                while ((bytesRead = bis.read(photo, 0, buffersize)) != -1)
                {
                    sb.put(photo, 0, bytesRead);
                }


                // 对字节数组Base64编码, 判断base64码是否超过32k,IE8只能加载32k以下
                BASE64Encoder encoder = new BASE64Encoder();
                base64Str = encoder.encode(sb.array());// 返回Base64编码过的字节数组字符串
                double percent = 1;
                while (base64Str.length() / 1024 > 32)
                {
                    percent = percent - 0.01;
                    base64Str = encoder.encode(sacleImageToBytes(percent));
                    System.out.println("******************************** " + base64Str.length() / 1024 + " kb");
                }
                //
            } catch (IOException e)
            {
                e.printStackTrace();
                throw new AppException("对图片进行base64编码失败!");

            } finally
            {
                try
                {
                    if (bis != null)
                        bis.close();
                    if (inputStream != null)
                        inputStream.close();
                } catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            map.put("picbase64", base64Str);
            return map;
        }
        
       
        /**
         * 获取图片的宽度
         * @return
         */
        public int getImgWidth()
        {
            return bi.getWidth();
        }

        /**
         * 获取图片的高度
         * @return
         */
        public int getImgHeight()
        {
            return bi.getHeight();
        }

        /**
         * 获取图片大小
         * @return
         * @throws AppException 
         */
        public double getImgSize() throws AppException
        {
            double size = 0;
            ByteArrayOutputStream baos = null;
            ImageOutputStream ios = null;
            try
            {
                baos = new ByteArrayOutputStream();
                ios = ImageIO.createImageOutputStream(baos);
                write(ios, null, "jpg", bi, null, 0.75f);
            } catch (IOException e)
            {
                throw new AppException("【getImgSize】获取图片大小发生错误:" + e.getMessage());
            } finally
            {
                try
                {
                    if (null != ios)
                    {
                        ios.close();
                    }
                    if (null != baos)
                    {
                        baos.close();
                    }
                } catch (IOException e)
                {
                    throw new AppException("【getImgSize】关闭流发生错误:" + e.getMessage());
                }
            }
            byte[] jpegData = baos.toByteArray();
            size = jpegData.length / 1024.00;
            return size;
        }
        /**
         * 编码输出图像。
         * 向图像文件中添加图像缩略图和设置图像压缩质量需要根据具体图像格式。
         * 
         * @param out 输出流。
         * @param listener 编码输出进度监听器。
         * @param formatName 包含格式非正式名称的 String,例如"jpg"。
         * @param image 图像。
         * @param thumbnails 缩略图集。
         * @param quality 压缩质量。
         * @throws java.io.IOException
         */
        public void write(ImageOutputStream out, IIOWriteProgressListener listener, String formatName,
                BufferedImage image, List thumbnails, float quality) throws IOException
        {
            if (out == null)
            {
                throw new IllegalArgumentException("OutputStream must be non null");
            }

            if (formatName == null)
            {
                throw new IllegalArgumentException("FormatName must be non null");
            }

            if (image == null)
            {
                throw new IllegalArgumentException("Image must be non null");
            }

            // 取得合适的 ImageWriter。
            Iterator writers = ImageIO.getImageWritersByFormatName(formatName);
            if (writers == null || !writers.hasNext())
            {
                throw new IllegalStateException("No " + formatName + " writers!");
            }
            ImageWriter writer = (ImageWriter) writers.next();

            ImageTypeSpecifier imageType = ImageTypeSpecifier.createFromRenderedImage(image);
            IIOMetadata metadata = writer.getDefaultImageMetadata(imageType, null);

            IIOImage iioImage = new IIOImage(image, thumbnails, metadata);

            ImageWriteParam param = writer.getDefaultWriteParam();
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(quality);

            writer.setOutput(out);
            writer.addIIOWriteProgressListener(listener);
            writer.write(null, iioImage, param);
            writer.dispose();
        }
        public byte[] sacleImageToBytes(double percent) throws IOException
        {
        	InputStream in = null;
        	BufferedInputStream bis = null;
    		ByteBuffer sb = null;
        	byte[] photo = null;
        	
        	double _width = this.scaleWidth * percent;
        	double _height = this.scaleHeight * percent;
        	
        	double rate1 = this.scaleWidth  / _width * 1.0;  
        	double rate2 = this.scaleHeight  / _height * 1.0;  
    		// 根据缩放比率大的进行缩放控制  
    		double rate = rate1 > rate2 ? rate1 : rate2;
    		
    		_width = (int)(this.scaleWidth / rate);
    		_height = (int)(this.scaleHeight / rate);
    		
    		try {
    			in = sacleImage(_width, _height, "jpg");
    			
    			sb = ByteBuffer.allocate(in.available());
    			int buffersize = 1024;
    			photo = new byte[buffersize]; // 缓存
    			int bytesRead = 0; // 读取数据临时变量
    			bis = new BufferedInputStream(in);
    			
    			while ((bytesRead = bis.read(photo, 0, buffersize)) != -1) {
    				sb.put(photo, 0, bytesRead);
    			}
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}finally{
    			if(in != null){
    				in.close();
    			}
    			if(bis != null){
    				bis.close();
    			}
    		}
    		
    		return sb.array();
        }
        public InputStream sacleImage(double _width, double _height, String imgType) throws IOException
        {
            double widthRatio = 1.0;
            double heightRatio = 1.0;

            if (this.getImgWidth() != _width)
            {
                widthRatio = _width / this.getImgWidth();
            }
            if (this.getImgHeight() != _height)
            {
                heightRatio = _height / this.getImgHeight();
            }
            byte[] bytes = null;
            if(widthRatio==1.0 && heightRatio==1.0){
            	bytes = InputStreamToByte(this.fis);
            }else{
                Image tempImg = bi.getScaledInstance(new Double(_width).intValue(), new Double(_height).intValue(),
                        BufferedImage.SCALE_SMOOTH);
    	        ByteArrayOutputStream bos = new ByteArrayOutputStream();
    	        AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(widthRatio, heightRatio), null);
    	        tempImg = op.filter(bi, null);
    	        ImageIO.write((BufferedImage) tempImg, imgType, bos);
    	        
    	        bytes = bos.toByteArray();
    	        if (bos != null)
    	        {
    	            bos.close();
    	        }
            }
            return new ByteArrayInputStream(bytes);
        }
        private byte[] InputStreamToByte(InputStream is) throws IOException {
    		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
    		int ch;
    		while ((ch = is.read()) != -1) {
    			bytestream.write(ch);
    		}
    		byte imgdata[] = bytestream.toByteArray();
    		bytestream.close();
    		return imgdata;
    	} 
        
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics