zoukankan      html  css  js  c++  java
  • 截图方式预览文件

     截图方式预览文件

      用户需求:文件在上传后,需要在页面展示类似windows平铺视图,这时候我们把文件保存一份截图,在平铺视图上展示截图即可。

      第一步:安装OpenOffice   http://www.openoffice.org/download/  当然服务器和本地根据平台不同下载不同版本

      第二步:启动OpenOffice服务(windows范例):

    cd C:\Program Files (x86)\OpenOffice 4\program
    soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
    pause

     

      转换工具类如下:

    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.lang.reflect.Method;
    import java.security.AccessController;
    import java.security.PrivilegedAction;
    import java.util.Date;
    import java.util.Iterator;
    
    import javax.imageio.IIOImage;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageWriter;
    import javax.imageio.stream.ImageOutputStream;
    
    import org.icepdf.core.pobjects.Document;
    import org.icepdf.core.pobjects.Page;
    import org.icepdf.core.util.GraphicsRenderingHints;
    
    import com.artofsolving.jodconverter.DocumentConverter;
    import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
    import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
    import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
    
    @SuppressWarnings("all")
    public class FileConvertUtil {
    
        private static final String[] OFFICE = new String[] { ".doc", ".docx", ".docx", ".ppt", ".pptx", ".xls", ".xlsx" };
        private static final String[] IMG = new String[] { ".bmp", ".gif", ".jpg", ".tif", ".png" };
        private static final String PDF = ".pdf";
        private static final String TXT = ".txt";
        public static final String FILETYPE_JPG = "jpg";
        public static final String SUFF_IMAGE = "." + FILETYPE_JPG;
        
        /**
         * 根据源文件生成一个预览图片
         * 
         * @param inputFilePath 文件路径
         * @param suffix 文件后缀
         * @return
         * @throws Exception
         */
        public static int convert(String inputFilePath, String suffix) throws Exception {
            int num = 0;
            if (PDF.equals(suffix)) {
                num = pdf2Jpg(inputFilePath);
            }
    
            if (TXT.equals(suffix)) {
                num = txt2pdf(inputFilePath);
            }
    
            for (String sf : OFFICE) {
                if (sf.equals(suffix)) {
                    num = Office2pdf(inputFilePath);
                    break;
                }
    
            }
            for (String sf : IMG) {
                if (sf.equals(suffix)) {
                    num = 1;
                    ImgConvert imgConvert = new ImgConvert();
                    imgConvert.convert(inputFilePath, "102x102", 102, 120);
                    imgConvert.convert(inputFilePath, "560x600", 560, 600);
                    break;
                }
    
            }
            return num;
        }
    
        /**
         * docx, .xls, .xlsx, .ppt, .pptx筿
         * 
         * @param inputFilePath
         */
        public static int txt2pdf(String inputFilePath) {
    
            int num = 0;
            try {
    
                OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
                connection.connect();
                DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
    
                String outputFilePath = getOutputFilePath(inputFilePath);
                File inputFile = new File(inputFilePath);
                inputFile = FileReName(inputFile, ".odt");
                if (inputFile.exists()) {
                    File outputFile = new File(outputFilePath);
                    if (!outputFile.getParentFile().exists()) {
                        outputFile.getParentFile().mkdirs();
                    }
                    converter.convert(inputFile, outputFile);
                }
                connection.disconnect();
                num = pdf2Jpg(outputFilePath);
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return num;
        }
    
        public static File FileReName(File file, String suffix) {
            String fileName = "/" + file.getName();
            String target = file.getParent() + fileName.substring(0, fileName.lastIndexOf(".")) + suffix;
            File file2 = new File(target);
            file.renameTo(file2);
            return file2;
        }
    
        /**
         * docx, .xls, .xlsx, .ppt, .pptx筿
         * 
         * @param inputFilePath
         */
        public static int Office2pdf(String inputFilePath) {
    
            int num = 0;
            try {
                long l=new Date().getTime();
                
                OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
                connection.connect();
                
                DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            
                String outputFilePath = getOutputFilePath(inputFilePath);
                File inputFile = new File(inputFilePath);
                if (inputFile.exists()) {
                    File outputFile = new File(outputFilePath);
                    if (!outputFile.getParentFile().exists()) {
                        outputFile.getParentFile().mkdirs();
                    }
                    converter.convert(inputFile, outputFile);
                }
                connection.disconnect();
                num = pdf2Jpg(outputFilePath);
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return num;
        }
    
        public static String getOutputFilePath(String inputFilePath) {
            String outputFilePath = inputFilePath.substring(0, inputFilePath.lastIndexOf(".")) + ".pdf";
            return outputFilePath;
        }
    
        /**
         * 
         * 清空缓冲
         * 
         * @param buffer
         */
        public static void unmap(final Object buffer) {
            AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    try {
                        Method getCleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]);
                        getCleanerMethod.setAccessible(true);
                        sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]);
                        cleaner.clean();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            });
        }
        
        public static void  toThumbnail(String filePath){
            BufferedImage bis = null;
            try {
                File fi = new File(filePath+".jpg"); //大图文件
                File fo = new File(filePath+"102x102.jpg"); //将要转换出的小图文件
    
                AffineTransform transform = new AffineTransform();
                bis = ImageIO.read(fi);
    
                int w = bis.getWidth();
                int h = bis.getHeight();
                double scale = (double)w/h;
    
                int nw = 102;
                int nh = (nw * h) / w;
                if(nh>102) {
                    nh = 102;
                    nw = (nh * w) / h;
                }
    
                double sx = (double)nw / w;
                double sy = (double)nh / h;
    
                transform.setToScale(sx,sy);
    
                AffineTransformOp ato = new AffineTransformOp(transform, null);
                BufferedImage bid = new BufferedImage(nw, nh, BufferedImage.TYPE_3BYTE_BGR);
                ato.filter(bis,bid);
                ImageIO.write(bid, "jpg", fo);
            } catch(Exception e) {
                e.printStackTrace();
            }
            finally{
                
                
            }
        }
    
    
        /**
         * 
         * @param inputFilePath
         * @return
         */
        public static int pdf2Jpg(String inputFilePath) {
             int maxPages =0;
             try{
    
                Document document = null;
         
                float rotation = 0f;
                String imagepath = inputFilePath.replaceAll(".pdf", ".jpg");
         
                document = new Document();
                document.setFile(inputFilePath);
                 maxPages = document.getPageTree().getNumberOfPages();
                System.out.println(maxPages);
         
                BufferedImage img = (BufferedImage) document.getPageImage(0,
                        GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation,1);
         
                Iterator iter = ImageIO.getImageWritersBySuffix(FILETYPE_JPG);
                ImageWriter writer = (ImageWriter) iter.next();
                File outFile = new File(imagepath);
                FileOutputStream out = new FileOutputStream(outFile);
                ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
                writer.setOutput(outImage);
                writer.write(new IIOImage(img, null, null));
                
                toThumbnail(imagepath.substring(0,imagepath.lastIndexOf(".jpg")));
                     
             } catch (Exception e) {
                 e.printStackTrace();
            }
            return maxPages;
        }
    
        
        public static void main(String[] args) {
                pdf2Jpg("E:/111.pdf");
        }
    
    }

      

      图片处理工具类:

    import java.awt.image.BufferedImage;
    import java.io.File;
    
    import javax.imageio.ImageIO;
    
    
    public class ImgConvert {
    
        private int width;
        private int height;
        private int scaleWidth;
        double support = (double) 3.0;
        double PI = (double) 3.14159265358978;
        double[] contrib;
        double[] normContrib;
        double[] tmpContrib;
        int startContrib, stopContrib;
        int nDots;
        int nHalfDots;
    
        //fromFileStr原图片地坿,saveToFileStr生成缩略图地坿,formatWideth生成图片宽度,formatHeight高度
        public void convert(String fromFileStr, String suffix, int formatWideth, int formatHeight) throws Exception {
            BufferedImage srcImage;
            
            int x = fromFileStr.lastIndexOf(".");
            int l = fromFileStr.length();
            String extName = fromFileStr.substring(x, l);
            String filename = fromFileStr.substring(0, x);
            
            File saveFile = new File(filename + suffix + extName);
            File fromFile = new File(fromFileStr);
            srcImage = javax.imageio.ImageIO.read(fromFile); // construct image
            int imageWideth = srcImage.getWidth(null);
            int imageHeight = srcImage.getHeight(null);
            int changeToWideth = 0;
            int changeToHeight = 0;
            if (imageWideth > 0 && imageHeight > 0) {
                if (imageWideth / imageHeight >= formatWideth / formatHeight) {
                    if (imageWideth > formatWideth) {
                        changeToWideth = formatWideth;
                        changeToHeight = (imageHeight * formatWideth) / imageWideth;
                    } else {
                        changeToWideth = imageWideth;
                        changeToHeight = imageHeight;
                    }
                } else {
                    if (imageHeight > formatHeight) {
                        changeToHeight = formatHeight;
                        changeToWideth = (imageWideth * formatHeight) / imageHeight;
                    } else {
                        changeToWideth = imageWideth;
                        changeToHeight = imageHeight;
                    }
                }
            }
            srcImage = imageZoomOut(srcImage, changeToWideth, changeToHeight);
            ImageIO.write(srcImage, "JPEG", saveFile);
        }
    
        public BufferedImage imageZoomOut(BufferedImage srcBufferImage, int w, int h) {
            width = srcBufferImage.getWidth();
            height = srcBufferImage.getHeight();
            scaleWidth = w;
            if (DetermineResultSize(w, h) == 1) {
                return srcBufferImage;
            }
            CalContrib();
            BufferedImage pbOut = HorizontalFiltering(srcBufferImage, w);
            BufferedImage pbFinalOut = VerticalFiltering(pbOut, h);
            return pbFinalOut;
        }
    
        private int DetermineResultSize(int w, int h) {
            double scaleH, scaleV;
            scaleH = (double) w / (double) width;
            scaleV = (double) h / (double) height;
            if (scaleH >= 1.0 && scaleV >= 1.0) {
                return 1;
            }
            return 0;
    
        }
    
        private double Lanczos(int i, int inWidth, int outWidth, double Support) {
            double x;
    
            x = (double) i * (double) outWidth / (double) inWidth;
    
            return Math.sin(x * PI) / (x * PI) * Math.sin(x * PI / Support) / (x * PI / Support);
    
        }
    
        private void CalContrib() {
            nHalfDots = (int) ((double) width * support / (double) scaleWidth);
            nDots = nHalfDots * 2 + 1;
            try {
                contrib = new double[nDots];
                normContrib = new double[nDots];
                tmpContrib = new double[nDots];
            } catch (Exception e) {
                e.printStackTrace();
                //System.out.println("init   contrib,normContrib,tmpContrib" + e);
            }
    
            int center = nHalfDots;
            contrib[center] = 1.0;
    
            double weight = 0.0;
            int i = 0;
            for (i = 1; i <= center; i++) {
                contrib[center + i] = Lanczos(i, width, scaleWidth, support);
                weight += contrib[center + i];
            }
    
            for (i = center - 1; i >= 0; i--) {
                contrib[i] = contrib[center * 2 - i];
            }
    
            weight = weight * 2 + 1.0;
    
            for (i = 0; i <= center; i++) {
                normContrib[i] = contrib[i] / weight;
            }
    
            for (i = center + 1; i < nDots; i++) {
                normContrib[i] = normContrib[center * 2 - i];
            }
        }
    
        private void CalTempContrib(int start, int stop) {
            double weight = 0;
    
            int i = 0;
            for (i = start; i <= stop; i++) {
                weight += contrib[i];
            }
    
            for (i = start; i <= stop; i++) {
                tmpContrib[i] = contrib[i] / weight;
            }
    
        }
    
        private int GetRedValue(int rgbValue) {
            int temp = rgbValue & 0x00ff0000;
            return temp >> 16;
        }
    
        private int GetGreenValue(int rgbValue) {
            int temp = rgbValue & 0x0000ff00;
            return temp >> 8;
        }
    
        private int GetBlueValue(int rgbValue) {
            return rgbValue & 0x000000ff;
        }
    
        private int ComRGB(int redValue, int greenValue, int blueValue) {
    
            return (redValue << 16) + (greenValue << 8) + blueValue;
        }
    
        private int HorizontalFilter(BufferedImage bufImg, int startX, int stopX, int start, int stop, int y, double[] pContrib) {
            double valueRed = 0.0;
            double valueGreen = 0.0;
            double valueBlue = 0.0;
            int valueRGB = 0;
            int i, j;
    
            for (i = startX, j = start; i <= stopX; i++, j++) {
                valueRGB = bufImg.getRGB(i, y);
    
                valueRed += GetRedValue(valueRGB) * pContrib[j];
                valueGreen += GetGreenValue(valueRGB) * pContrib[j];
                valueBlue += GetBlueValue(valueRGB) * pContrib[j];
            }
    
            valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen), Clip((int) valueBlue));
            return valueRGB;
    
        }
    
        private BufferedImage HorizontalFiltering(BufferedImage bufImage, int iOutW) {
            int dwInW = bufImage.getWidth();
            int dwInH = bufImage.getHeight();
            int value = 0;
            BufferedImage pbOut = new BufferedImage(iOutW, dwInH, BufferedImage.TYPE_INT_RGB);
    
            for (int x = 0; x < iOutW; x++) {
    
                int startX;
                int start;
                int X = (int) (((double) x) * ((double) dwInW) / ((double) iOutW) + 0.5);
                int y = 0;
    
                startX = X - nHalfDots;
                if (startX < 0) {
                    startX = 0;
                    start = nHalfDots - X;
                } else {
                    start = 0;
                }
    
                int stop;
                int stopX = X + nHalfDots;
                if (stopX > (dwInW - 1)) {
                    stopX = dwInW - 1;
                    stop = nHalfDots + (dwInW - 1 - X);
                } else {
                    stop = nHalfDots * 2;
                }
    
                if (start > 0 || stop < nDots - 1) {
                    CalTempContrib(start, stop);
                    for (y = 0; y < dwInH; y++) {
                        value = HorizontalFilter(bufImage, startX, stopX, start, stop, y, tmpContrib);
                        pbOut.setRGB(x, y, value);
                    }
                } else {
                    for (y = 0; y < dwInH; y++) {
                        value = HorizontalFilter(bufImage, startX, stopX, start, stop, y, normContrib);
                        pbOut.setRGB(x, y, value);
                    }
                }
            }
    
            return pbOut;
    
        }
    
        private int VerticalFilter(BufferedImage pbInImage, int startY, int stopY, int start, int stop, int x, double[] pContrib) {
            double valueRed = 0.0;
            double valueGreen = 0.0;
            double valueBlue = 0.0;
            int valueRGB = 0;
            int i, j;
    
            for (i = startY, j = start; i <= stopY; i++, j++) {
                valueRGB = pbInImage.getRGB(x, i);
    
                valueRed += GetRedValue(valueRGB) * pContrib[j];
                valueGreen += GetGreenValue(valueRGB) * pContrib[j];
                valueBlue += GetBlueValue(valueRGB) * pContrib[j];
            }
    
            valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen), Clip((int) valueBlue));
            return valueRGB;
    
        }
    
        private BufferedImage VerticalFiltering(BufferedImage pbImage, int iOutH) {
            int iW = pbImage.getWidth();
            int iH = pbImage.getHeight();
            int value = 0;
            BufferedImage pbOut = new BufferedImage(iW, iOutH, BufferedImage.TYPE_INT_RGB);
    
            for (int y = 0; y < iOutH; y++) {
    
                int startY;
                int start;
                int Y = (int) (((double) y) * ((double) iH) / ((double) iOutH) + 0.5);
    
                startY = Y - nHalfDots;
                if (startY < 0) {
                    startY = 0;
                    start = nHalfDots - Y;
                } else {
                    start = 0;
                }
    
                int stop;
                int stopY = Y + nHalfDots;
                if (stopY > (int) (iH - 1)) {
                    stopY = iH - 1;
                    stop = nHalfDots + (iH - 1 - Y);
                } else {
                    stop = nHalfDots * 2;
                }
    
                if (start > 0 || stop < nDots - 1) {
                    CalTempContrib(start, stop);
                    for (int x = 0; x < iW; x++) {
                        value = VerticalFilter(pbImage, startY, stopY, start, stop, x, tmpContrib);
                        pbOut.setRGB(x, y, value);
                    }
                } else {
                    for (int x = 0; x < iW; x++) {
                        value = VerticalFilter(pbImage, startY, stopY, start, stop, x, normContrib);
                        pbOut.setRGB(x, y, value);
                    }
                }
            }
    
            return pbOut;
    
        }
    
        int Clip(int x) {
            if (x < 0)
                return 0;
            if (x > 255)
                return 255;
            return x;
        }
    
    }
  • 相关阅读:
    理解CSS定位中的overflow和visibility属性
    理解CSS定位中的position
    理解margin负值,实现经典布局
    理解CSS定位中的float
    CSS表格属性
    图解一步步安装SharePoint Foundation 2010
    Gladinet Cloud Desktop Professional License(专业版序列号)
    配置SharePoint Foundation 2010基于表单的验证支持
    快逸报表部署心得
    如何阅读公司财务报告
  • 原文地址:https://www.cnblogs.com/meitanzai/p/5825998.html
Copyright © 2011-2022 走看看