Ant task to extract image sizes (height, width) from PNG and JPEG files?

In accordance with the recommendations of Google Page Speed, I want to Specify image sizes in "Optimize browser rendering."

Specifying the width and height for all images allows for faster elimination of the need for unnecessary overcharges and repaints.

I am exploring ways of passing through image files (PNG, JPEG) in my project of static content and outputting a file with the path and file name of each image, as well as the height and width in pixels. Then I would use this to help me build tags using the src attribute data to find the values ​​used for the height and width attributes.

\images\logo.png,100,25

My first ideas were looking for the ANT task, since our static content structure uses Ant for other purposes (for example, using the YUI Compressor in JavaScript and CSS files). I am also open to other ideas, including other methods to solve this problem. I would prefer not to do this work manually.

+5
source share
3 answers

You can try this https://github.com/mattwildig/image-size-report-task , which I did just for this question.

+4
source

( ). : , , Ant java?, . , .

script :

<project name="ImagesTask" basedir="." default="test">
    <target name="init">
        <taskdef name="images" classname="ImageInfoTask" classpath="..\dist\ImageTask.jar"/>
    </target>
    <target name="test" depends="init">
        <images outputFile="data/images.xml">
            <fileset dir="data" includes="images/**/*.jpg"/>
            <fileset dir="data" includes="images/**/*.gif"/>
            <fileset dir="data" includes="images/**/*.png"/>
        </images>
    </target>
</project>

Java ( ):

public class ImageInfoTask extends Task {

    private String outputFile;
    private List fileSetList = new ArrayList();
    private PrintStream outputFileStream;

    public void setOutputFile(String outputFile) {
        this.outputFile = outputFile.replace("/", File.separator);
    }

    public void addFileset(FileSet fileset) {
        fileSetList.add(fileset);
    }

    protected void validate() {
        if (outputFile == null) {
            throw new BuildException("file not set");
        }

        if (fileSetList.size() < 1) {
            throw new BuildException("fileset not set");
        }
    }

    protected void openOutputFile() throws IOException {
        FileOutputStream out = new FileOutputStream(this.outputFile);

        // Connect print stream to the output stream
        this.outputFileStream = new PrintStream(out, true, "UTF-8");

        this.outputFileStream.println("<images>");
    }

    protected void writeImgToOutputFile(String filename, Dimension dim) {
        String imgTag = "  <img src=\"/" + filename.replace("\\", "/")
                + "\" height=\"" + dim.height + "\" width=\"" + dim.width
                + "\" />";

        this.outputFileStream.println(imgTag);
    }

    protected void closeOutputFile() {
        this.outputFileStream.println("</images>");

        this.outputFileStream.close();
    }

    @Override
    public void execute() {
        validate();

        try {
            openOutputFile();

            for (Iterator itFSets = fileSetList.iterator(); itFSets.hasNext();) {
                FileSet fs = (FileSet) itFSets.next();
                DirectoryScanner ds = fs.getDirectoryScanner(getProject());
                String[] includedFiles = ds.getIncludedFiles();
                for (int i = 0; i < includedFiles.length; i++) {
                    String filename = includedFiles[i];

                    Dimension dim = getImageDim(ds.getBasedir() + File.separator + filename);
                    if (dim != null) {
                        writeImgToOutputFile(filename, dim);
                    }
                }
            }

            closeOutputFile();
        }  catch (IOException ex) {
            log(ex.getMessage());
        }
    }

    private Dimension getImageDim(final String path) {
        Dimension result = null;
        String suffix = this.getFileSuffix(path);
        Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
        if (iter.hasNext()) {
            ImageReader reader = iter.next();
            try {
                ImageInputStream stream = new FileImageInputStream(new File(path));
                reader.setInput(stream);
                int width = reader.getWidth(reader.getMinIndex());
                int height = reader.getHeight(reader.getMinIndex());
                result = new Dimension(width, height);
            } catch (IOException e) {
                log(path + ": " + e.getMessage());
            } finally {
                reader.dispose();
            }
        }
        return result;
    }

    private String getFileSuffix(final String path) {
        String result = null;
        if (path != null) {
            result = "";
            if (path.lastIndexOf('.') != -1) {
                result = path.substring(path.lastIndexOf('.'));
                if (result.startsWith(".")) {
                    result = result.substring(1);
                }
            }
        }
        return result;
    }
}
+1

I do not know about an ant task that is easily accessible, but should be relatively easy to write. In PNG format, the image size is stored at the beginning of the file in the IHDR header. Google has many PNG parser patterns — for example, this . Complete it in the ant task, and you're done.

0
source

All Articles