POI插入图片的时候,使用resize函数还是变形的问题

最近在excel2000的版本上用POI插入图片的时候,即使调用resize方法,插入的图片还是走形了。

     patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_PNG).resize(1.0)

最近只好跟进POI的代码中debug。发现是宽度计算的对。

    public HSSFClientAnchor getPreferredSize(double scale){
        HSSFClientAnchor anchor = (HSSFClientAnchor)getAnchor();

        Dimension size = getImageDimension();
        double scaledWidth = size.getWidth() * scale;
        double scaledHeight = size.getHeight() * scale;

        float w = 0;

        //space in the leftmost cell
        w += getColumnWidthInPixels(anchor.col1)*(1 - (float)anchor.dx1/1024);
        short col2 = (short)(anchor.col1 + 1);
        int dx2 = 0;

        while(w < scaledWidth){
            w += getColumnWidthInPixels(col2++);
        }

        if(w > scaledWidth) {
            //calculate dx2, offset in the rightmost cell
            col2--;
            double cw = getColumnWidthInPixels(col2);
            double delta = w - scaledWidth;
            dx2 = (int)((cw-delta)/cw*1024);
        }
        anchor.col2 = col2;
        anchor.dx2 = dx2;

        float h = 0;
        h += (1 - (float)anchor.dy1/256)* getRowHeightInPixels(anchor.row1);
        int row2 = anchor.row1 + 1;
        int dy2 = 0;

        while(h < scaledHeight){
            h += getRowHeightInPixels(row2++);
        }
        if(h > scaledHeight) {
            row2--;
            double ch = getRowHeightInPixels(row2);
            double delta = h - scaledHeight;
            dy2 = (int)((ch-delta)/ch*256);
        }
        anchor.row2 = row2;
        anchor.dy2 = dy2;

        return anchor;
    }

    private float getColumnWidthInPixels(int column){

        int cw = patriarch.sheet.getColumnWidth(column);
        float px = getPixelWidth(column);

        return cw/px;
    }

    private float getRowHeightInPixels(int i){

        HSSFRow row = patriarch.sheet.getRow(i);
        float height;
        if(row != null) height = row.getHeight();
        else height = patriarch.sheet.getDefaultRowHeight();

        return height/PX_ROW;
    }

    private float getPixelWidth(int column){

        int def = patriarch.sheet.getDefaultColumnWidth()*256;
        int cw = patriarch.sheet.getColumnWidth(column);

        return cw == def ? PX_DEFAULT : PX_MODIFIED;
    }

找到了可能的问题点了。
return cw == def ? PX_DEFAULT : PX_MODIFIED;
    /**
     * width of 1px in columns with default width in units of 1/256 of a character width
     */
    private static final float PX_DEFAULT = 32.00f;
    /**
     * width of 1px in columns with overridden width in units of 1/256 of a character width
     */
    private static final float PX_MODIFIED = 36.56f;

这个地方的PX_MODIFIED = 36.56f造成了走形。

修改方法把PX_MODIFIED = 36.56f改为PX_MODIFIED = 32.00f;即可。   //这个只是在excel2000中测试的。其他版本可能要具体测试一下。


你可能感兴趣的:(POI插入图片的时候,使用resize函数还是变形的问题)