本文实例为大家分享了java用Excel将图片画出来的具体代码,供大家参考,具体内容如下
能够将任何图片在excel上利用单元格背景完整的描绘出来。
像网络上出现的用excel画出超级玛丽等等,各种图片都能在excel上"画"出来。
图片我没有经过特殊处理,所以转换的图片不能太大,有多大的图片就要有多少的单元格。如640*480就有307200的单元格。
如要转换的图片:
转换后在excel中的效果:
没多大意义练练手:
import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Locale; import javax.swing.ImageIcon; import jxl.Workbook; import jxl.WorkbookSettings; import jxl.format.Colour; import jxl.read.biff.BiffException; import jxl.write.Label; import jxl.write.WritableCellFormat; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class Helper { private BufferedImage getBufferedImage(String filepath) { ImageIcon imgicon=new ImageIcon(filepath); BufferedImage bufferedImage = new BufferedImage(imgicon.getIconWidth(),imgicon.getIconHeight(),BufferedImage.TYPE_INT_RGB); bufferedImage.createGraphics().drawImage(imgicon.getImage(), 0, 0,null); return bufferedImage; } private Colour getNearestColour(Color awtColor) { Colour color = null; Colour[] colors = Colour.getAllColours(); if ((colors != null) && (colors.length > 0)) { Colour crtColor = null; int[] rgb = null; int diff = 0; int minDiff = 999; for (int i = 0; i < colors.length; i++) { crtColor = colors[i]; rgb = new int[3]; rgb[0] = crtColor.getDefaultRGB().getRed(); rgb[1] = crtColor.getDefaultRGB().getGreen(); rgb[2] = crtColor.getDefaultRGB().getBlue(); diff = Math.abs(rgb[0] - awtColor.getRed()) + Math.abs(rgb[1] - awtColor.getGreen()) + Math.abs(rgb[2] - awtColor.getBlue()); if (diff < minDiff) { minDiff = diff; color = crtColor; } } } if (color == null) color = Colour.BLACK; return color; } public void exec(String convertFromImage,String createxls) throws Exception { WorkbookSettings ws = new WorkbookSettings(); ws.setLocale(new Locale("en", "EN")); WritableWorkbook workbook = Workbook.createWorkbook(new File(createxls), ws); WritableSheet s2 = workbook.createSheet("picture", 0); BufferedImage buffimage= getBufferedImage(convertFromImage); int width=buffimage.getWidth(); int heigh=buffimage.getHeight(); for(int i=0;i<width;i++) { for(int h=0;h<heigh;h++) { WritableCellFormat greyBackground = new WritableCellFormat(); Color c = new Color(buffimage.getRGB(i, h)); greyBackground.setBackground( getNearestColour(c) ); Label lr = new Label(i, h, "", greyBackground); s2.addCell(lr); } } //写入Excel对象 workbook.write(); workbook.close(); } /** * @param args * @throws IOException * @throws BiffException */ public static void main(String[] args) throws Exception { Helper helper=new Helper(); System.out.println("输入的图片:"+args[0]); System.out.println("输出的excel:"+args[1]); System.out.println("转换开始"); //转换执行的方法参数 args[0]输入的图片路径 args[1]输出的excel路径 // helper.exec( "mslogo.jpg","1.xls"); helper.exec(args[0],args[1]); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。