【JAVA】桌宠开发发现的有趣内容(1) java 图片镜像 反转的方法。

有两种反转图片的方式一种是通过AffineTransform进行反转。另一种是通过图片字节处理来达到反转生成的目的。

字节处理代码,推荐

ImageIcon icon = null;
			
			try {
				BufferedImage img = ImageIO.read(new FileInputStream(imgUrl));
				final BufferedImage cimg = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
				
				for (int y = 0; y < img.getHeight(); ++y) {
					for (int x = 0; x < img.getWidth(); ++x) {
						cimg.setRGB(cimg.getWidth() - x - 1, y, cimg.getRGB(x, y));
					}
				}
				icon = new ImageIcon(cimg);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		int picWidth = icon.getIconWidth(),pinHeight = icon.getIconHeight();
		icon.setImage(icon.getImage().getScaledInstance(picWidth,pinHeight, Image.SCALE_FAST));
		
		jLabel.setBounds(0,0,picWidth,pinHeight);
		jLabel.setIcon(icon);

AffineTransform方法进行反转

		BufferedImage sourceImage = null;
		sourceImage = ImageIO.read(new FileInputStream(imgUrl));
	        BufferedImage dstImage = null; 
	        AffineTransform transform = new   AffineTransform(-1,0,0,1,sourceImage.getWidth()-1,0);//水平翻转   
	        //AffineTransform transform = new   AffineTransform(1,0,0,-1,0,sourceImage.getHeight()-1);//垂直翻转   
	         //AffineTransform transform = new   AffineTransform(-1,0,0,-1,sourceImage.getWidth()-1,sourceImage.getHeight()-1);//旋转180度   
	        AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);   
	        dstImage = op.filter(sourceImage, null); 
	        icon = new ImageIcon(dstImage);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		int picWidth = icon.getIconWidth(),pinHeight = icon.getIconHeight();
    		icon.setImage(icon.getImage().getScaledInstance(picWidth,pinHeight, Image.SCALE_FAST));
    		
    		jLabel.setBounds(0,0,picWidth,pinHeight);
    		jLabel.setIcon(icon);

两种方法都比较好用,图片转换和镜像反转,主要推荐第一种。

你可能感兴趣的:(java)