Example usage for javax.imageio ImageIO read

List of usage examples for javax.imageio ImageIO read

Introduction

In this page you can find the example usage for javax.imageio ImageIO read.

Prototype

public static BufferedImage read(ImageInputStream stream) throws IOException 

Source Link

Document

Returns a BufferedImage as the result of decoding a supplied ImageInputStream with an ImageReader chosen automatically from among those currently registered.

Usage

From source file:frankhassanabad.com.github.Jasperize.java

/**
 * Main method to call through Java in order to take a LinkedInProfile on disk and load it.
 *
 * @param args command line arguments where the options are stored
 * @throws FileNotFoundException Thrown if any file its expecting cannot be found.
 * @throws JRException  If there's generic overall Jasper issues.
 * @throws ParseException If there's command line parsing issues.
 *///from w ww.j  a va  2 s  .com
public static void main(String[] args) throws IOException, JRException, ParseException {

    Options options = new Options();
    options.addOption("h", "help", false, "Shows the help documentation");
    options.addOption("v", "version", false, "Shows the help documentation");
    options.addOption("cl", "coverLetter", false, "Utilizes a cover letter defined in coverletter.xml");
    options.addOption("sig", true, "Picture of your signature to add to the cover letter.");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jasperize [OPTIONS] [InputJrxmlFile] [OutputExportFile]", options);
        System.exit(0);
    }
    if (cmd.hasOption("v")) {
        System.out.println("Version:" + version);
        System.exit(0);
    }
    boolean useCoverLetter = cmd.hasOption("cl");
    String signatureLocation = cmd.getOptionValue("sig");
    BufferedImage signatureImage = null;
    if (signatureLocation != null) {
        signatureImage = ImageIO.read(new File(signatureLocation));
        ;
    }

    @SuppressWarnings("unchecked")
    List<String> arguments = cmd.getArgList();

    final String jrxmlFile;
    final String jasperOutput;
    if (arguments.size() == 2) {
        jrxmlFile = arguments.get(0);
        jasperOutput = arguments.get(1);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else if (arguments.size() == 3) {
        jrxmlFile = arguments.get(1);
        jasperOutput = arguments.get(2);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else {
        System.out.println("Using the default arguments of:");
        jrxmlFile = "data/jasperTemplates/resume1.jrxml";
        jasperOutput = "data/jasperOutput/linkedInResume.pdf";
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    }

    final String compiledMasterFile;
    final String outputType;
    final String jrPrintFile;
    //Split the inputFile
    final String[] inputSplit = jrxmlFile.split("\\.");
    if (inputSplit.length != 2 || !(inputSplit[1].equalsIgnoreCase("jrxml"))) {
        //Error
        System.out.println("Your [InputjrxmlFile] (1st argument) should have a jrxml extension like such:");
        System.out.println("    data/jasperTemplates/resume1.jrxml");
        System.exit(1);
    }
    //Split the outputFile
    final String[] outputSplit = jasperOutput.split("\\.");
    if (outputSplit.length != 2) {
        //Error
        System.out.println("Your [OutputExportFile] (2nd argument) should have a file extension like such:");
        System.out.println("    data/jasperOutput/linkedInResume.pdf");
        System.exit(1);
    }

    File inputFile = new File(inputSplit[0]);
    String inputFileName = inputFile.getName();
    String inputFileParentPath = inputFile.getParent();

    File outputFile = new File(outputSplit[0]);
    String outputFileParentPath = outputFile.getParent();

    System.out.println("Compiling report(s)");
    compileAllJrxmlTemplateFiles(inputFileParentPath, outputFileParentPath);
    System.out.println("Done compiling report(s)");

    compiledMasterFile = outputFileParentPath + File.separator + inputFileName + ".jasper";
    jrPrintFile = outputFileParentPath + File.separator + inputFileName + ".jrprint";

    System.out.println("Filling report: " + compiledMasterFile);
    Reporting.fill(compiledMasterFile, useCoverLetter, signatureImage);
    System.out.println("Done filling reports");
    outputType = outputSplit[1];
    System.out.println("Creating output export file of: " + jasperOutput);
    if (outputType.equalsIgnoreCase("pdf")) {
        Reporting.pdf(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("pptx")) {
        Reporting.pptx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("docx")) {
        Reporting.docx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("odt")) {
        Reporting.odt(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("xhtml")) {
        Reporting.xhtml(jrPrintFile, jasperOutput);
    }
    System.out.println("Done creating output export file of: " + jasperOutput);
}

From source file:acmi.l2.clientmod.l2_version_switcher.Main.java

public static void main(String[] args) {
    if (args.length != 3 && args.length != 4) {
        System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>");
        System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME
                + " 1 \"system\\*\"");
        System.out.println(//  w  ww  .  j  a  va  2s. co m
                "         l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48");
        System.exit(0);
    }

    List<String> argsList = new ArrayList<>(Arrays.asList(args));
    String host = argsList.get(0);
    String game = argsList.get(1);
    int version = Integer.parseInt(argsList.get(2));
    Helper helper = new Helper(host, game, version);
    boolean available = false;

    try {
        available = helper.isAvailable();
    } catch (IOException e) {
        System.err.print(e.getClass().getSimpleName());
        if (e.getMessage() != null) {
            System.err.print(": " + e.getMessage());
        }

        System.err.println();
    }

    System.out.println(String.format("Version %d available: %b", version, available));
    if (!available) {
        System.exit(0);
    }

    List<FileInfo> fileInfoList = null;
    try {
        fileInfoList = helper.getFileInfoList();
    } catch (IOException e) {
        System.err.println("Couldn\'t get file info map");
        System.exit(1);
    }

    boolean splash = argsList.remove("--splash");
    if (splash) {
        Optional<FileInfo> splashObj = fileInfoList.stream()
                .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny();
        if (splashObj.isPresent()) {
            try (InputStream is = new FilterInputStream(
                    Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) {
                @Override
                public int read() throws IOException {
                    int b = super.read();
                    if (b >= 0)
                        b ^= 0x36;
                    return b;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    int r = super.read(b, off, len);
                    if (r >= 0) {
                        for (int i = 0; i < r; i++)
                            b[off + i] ^= 0x36;
                    }
                    return r;
                }
            }) {
                new DataInputStream(is).readFully(new byte[28]);
                BufferedImage bi = ImageIO.read(is);

                JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath());
                frame.setContentPane(new JComponent() {
                    {
                        setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
                    }

                    @Override
                    protected void paintComponent(Graphics g) {
                        g.drawImage(bi, 0, 0, null);
                    }
                });
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Splash not found");
        }
        return;
    }

    String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null;

    File l2Folder = new File(System.getProperty("user.dir"));
    List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> {
        String filePath = separatorsToSystem(fi.getPath());

        if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE))
            return false;
        File file = new File(l2Folder, filePath);

        try {
            if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) {
                System.out.println(filePath + ": OK");
                return false;
            }
        } catch (IOException e) {
            System.out.println(filePath + ": couldn't check hash: " + e);
            return true;
        }

        System.out.println(filePath + ": need update");
        return true;
    }).collect(Collectors.toList());

    List<String> errors = Collections.synchronizedList(new ArrayList<>());
    ExecutorService executor = Executors.newFixedThreadPool(16);
    CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> {
        String filePath = separatorsToSystem(fi.getPath());
        File file = new File(l2Folder, filePath);

        File folder = file.getParentFile();
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                errors.add(filePath + ": couldn't create parent dir");
                return;
            }
        }

        try (InputStream input = Util
                .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath())));
                OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
            byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)];
            int pos = 0;
            int r;
            while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) {
                pos += r;
                if (pos == buffer.length) {
                    output.write(buffer, 0, pos);
                    pos = 0;
                }
            }
            if (pos != 0) {
                output.write(buffer, 0, pos);
            }
            System.out.println(filePath + ": OK");
        } catch (IOException e) {
            String msg = filePath + ": FAIL: " + e.getClass().getSimpleName();
            if (e.getMessage() != null) {
                msg += ": " + e.getMessage();
            }
            errors.add(msg);
        }
    }, executor)).toArray(CompletableFuture[]::new);
    CompletableFuture.allOf(tasks).thenRun(() -> {
        for (String err : errors)
            System.err.println(err);
        executor.shutdown();
    });
}

From source file:com.zarkonnen.longan.Main.java

public static void main(String[] args) throws IOException {
    // Use Apache Commons CLI (packaged into the Jar) to parse command line options.
    Options options = new Options();
    Option helpO = OptionBuilder.withDescription("print help").create("h");
    Option versionO = OptionBuilder.withDescription("print version").create("v");
    Option outputO = OptionBuilder.withDescription("output file").withLongOpt("out").hasArg()
            .withArgName("file").create("o");
    Option formatO = OptionBuilder
            .withDescription("output format: one of plaintext (default) and visualize (debug output in png)")
            .hasArg().withArgName("format").withLongOpt("format").create();
    Option serverO = OptionBuilder.withDescription("launches server mode: Server mode reads "
            + "command line strings one per line exactly as above. If no output file is "
            + "specified, returns a line containing the number of output lines before the "
            + "output. If there is an error, returns a single line with the error message. "
            + "Shut down server by sending \"quit\".").withLongOpt("server").create();
    Option openCLO = OptionBuilder
            .withDescription(//  w  w w.j a v  a 2s  .  c  o  m
                    "enables use of the graphics card to " + "support the OCR system. Defaults to true.")
            .withLongOpt("enable-opencl").hasArg().withArgName("enabled").create();
    options.addOption(helpO);
    options.addOption(versionO);
    options.addOption(outputO);
    options.addOption(formatO);
    options.addOption(serverO);
    options.addOption(openCLO);
    CommandLineParser clp = new GnuParser();
    try {
        CommandLine line = clp.parse(options, args);
        if (line.hasOption("h")) {
            new HelpFormatter().printHelp(INVOCATION, options);
            System.exit(0);
        }
        if (line.hasOption("v")) {
            System.out.println(Longan.VERSION);
            System.exit(0);
        }
        boolean enableOpenCL = true;
        if (line.hasOption("enable-opencl")) {
            enableOpenCL = line.getOptionValue("enable-opencl").toLowerCase().equals("true")
                    || line.getOptionValue("enable-opencl").equals("1");
        }
        if (line.hasOption("server")) {
            Longan longan = Longan.getDefaultImplementation(enableOpenCL);
            BufferedReader inputR = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String input = inputR.readLine();
                if (input.trim().equals("quit")) {
                    return;
                }
                String[] args2 = splitInput(input);
                Options o2 = new Options();
                o2.addOption(outputO);
                o2.addOption(formatO);
                try {
                    line = clp.parse(o2, args2);

                    File outFile = null;
                    if (line.hasOption("o")) {
                        outFile = new File(line.getOptionValue("o"));
                    }

                    ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext"));
                    if (format != DEFAULT_FORMAT && outFile == null) {
                        System.out.println("You must specify an output file for non-plaintext output.");
                        continue;
                    }

                    if (line.getArgList().isEmpty()) {
                        System.out.println("Please specify an input image.");
                        continue;
                    }
                    if (line.getArgList().size() > 1) {
                        System.err.println("Please specify one input image at a time");
                        continue;
                    }

                    File inFile = new File((String) line.getArgList().get(0));

                    if (!inFile.exists()) {
                        System.out.println("The input image does not exist.");
                        continue;
                    }

                    try {
                        Result result = longan.process(ImageIO.read(inFile));
                        if (outFile == null) {
                            String txt = DEFAULT_FORMAT.convert(result);
                            System.out.println(numNewlines(txt) + 1);
                            System.out.print(txt);
                        } else {
                            if (outFile.getAbsoluteFile().getParentFile() != null
                                    && !outFile.getAbsoluteFile().getParentFile().exists()) {
                                outFile.getParentFile().mkdirs();
                            }
                            FileOutputStream fos = new FileOutputStream(outFile);
                            try {
                                format.write(result, fos);
                            } finally {
                                fos.close();
                            }
                        }
                    } catch (Exception e) {
                        System.out.println("Processing error: " + exception(e));
                    }
                } catch (ParseException e) {
                    System.out.println("Input not recognized: " + exception(e));
                }
            } // End server loop
        } else {
            // Single invocation
            File outFile = null;
            if (line.hasOption("o")) {
                outFile = new File(line.getOptionValue("o"));
            }

            ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext"));
            if (format != DEFAULT_FORMAT && outFile == null) {
                System.err.println("You must specify an output file for non-plaintext output.");
                System.exit(1);
            }

            if (line.getArgList().isEmpty()) {
                System.err.println("Please specify an input image.");
                new HelpFormatter().printHelp(INVOCATION, options);
                System.exit(1);
            }
            if (line.getArgList().size() > 1) {
                System.err.println("Please specify one input image only. To process multiple "
                        + "images, use server mode.");
                System.exit(1);
            }
            File inFile = new File((String) line.getArgList().get(0));

            if (!inFile.exists()) {
                System.err.println("The input image does not exist.");
                System.exit(1);
            }

            try {
                Result result = Longan.getDefaultImplementation(enableOpenCL).process(ImageIO.read(inFile));
                if (outFile == null) {
                    String txt = DEFAULT_FORMAT.convert(result);
                    System.out.print(txt);
                } else {
                    if (outFile.getAbsoluteFile().getParentFile() != null
                            && !outFile.getAbsoluteFile().getParentFile().exists()) {
                        outFile.getParentFile().mkdirs();
                    }
                    FileOutputStream fos = new FileOutputStream(outFile);
                    try {
                        format.write(format.convert(result), fos);
                    } finally {
                        fos.close();
                    }
                }
            } catch (Exception e) {
                System.err.println("Processing error: " + exception(e));
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.println("Parsing command line input failed: " + exception(e));
        System.exit(1);
    }
}

From source file:com.diversityarrays.dal.server.DalServer.java

public static void main(String[] args) {

    String host = null;/*from w  ww . j av  a2 s  . c om*/
    int port = DalServerUtil.DEFAULT_DAL_SERVER_PORT;

    int inactiveMins = DalServerUtil.DEFAULT_MAX_INACTIVE_MINUTES;

    File docRoot = null;

    String serviceName = null;

    for (int i = 0; i < args.length; ++i) {
        String argi = args[i];
        if (argi.startsWith("-")) {
            if ("--".equals(argi)) {
                break;
            }

            if ("-version".equals(argi)) {
                System.out.println(DAL_SERVER_VERSION);
                System.exit(0);
            }

            if ("-help".equals(argi)) {
                giveHelpThenExit(0);
            }

            if ("-docroot".equals(argi)) {
                if (++i >= args.length || args[i].startsWith("-")) {
                    fatal("missing value for " + argi);
                }
                docRoot = new File(args[i]);
            } else if ("-sqllog".equals(argi)) {
                SqlUtil.logger = Logger.getLogger(SqlUtil.class.getName());
            } else if ("-expire".equals(argi)) {
                if (++i >= args.length || args[i].startsWith("-")) {
                    fatal("missing value for " + argi);
                }

                try {
                    inactiveMins = Integer.parseInt(args[i], 10);
                    if (inactiveMins <= 0) {
                        fatal("invalid minutes: " + args[i]);
                    }
                } catch (NumberFormatException e) {
                    fatal("invalid minutes: " + args[i]);
                }
            } else if ("-localhost".equals(argi)) {
                host = "localhost";
            } else if ("-port".equals(argi)) {
                if (++i >= args.length || args[i].startsWith("-")) {
                    fatal("missing value for " + argi);
                }
                try {
                    port = Integer.parseInt(args[i], 10);
                    if (port < 0 || port > 65535) {
                        fatal("invalid port number: " + args[i]);
                    }
                } catch (NumberFormatException e) {
                    fatal("invalid port number: " + args[i]);
                }
            } else {
                fatal("invalid option: " + argi);
            }
        } else {
            if (serviceName != null) {
                fatal("multiple serviceNames not supported: " + argi);
            }
            serviceName = argi;
        }
    }

    final DalServerPreferences preferences = new DalServerPreferences(
            Preferences.userNodeForPackage(DalServer.class));

    if (docRoot == null) {
        docRoot = preferences.getWebRoot(new File(System.getProperty("user.dir"), "www"));
    }

    DalServer server = null;

    if (serviceName != null && docRoot.isDirectory()) {
        try {
            DalDatabase db = createDalDatabase(serviceName, preferences);
            if (db.isInitialiseRequired()) {
                Closure<String> progress = new Closure<String>() {
                    @Override
                    public void execute(String msg) {
                        System.out.println("Database Initialisation: " + msg);
                    }
                };
                db.initialise(progress);
            }
            server = create(preferences, host, port, docRoot, db);
        } catch (NoServiceException e) {
            throw new RuntimeException(e);
        } catch (DalDbException e) {
            throw new RuntimeException(e);
        }
    }

    Image serverIconImage = null;
    InputStream imageIs = DalServer.class.getResourceAsStream("dalserver-24.png");
    if (imageIs != null) {
        try {
            serverIconImage = ImageIO.read(imageIs);

            if (Util.isMacOS()) {
                try {
                    MacApplication macapp = new MacApplication(null);
                    macapp.setDockIconImage(serverIconImage);
                } catch (MacApplicationException e) {
                    System.err.println(e.getMessage());
                }
            }

        } catch (IOException ignore) {
        }
    }

    if (server != null) {
        server.setMaxInactiveMinutes(inactiveMins);
    } else {
        AskServerParams asker = new AskServerParams(serverIconImage, null, "DAL Server Start", docRoot,
                preferences);
        GuiUtil.centreOnScreen(asker);
        asker.setVisible(true);

        if (asker.cancelled) {
            System.exit(0);
        }

        host = asker.dalServerHostName;
        port = asker.dalServerPort;
        inactiveMins = asker.maxInactiveMinutes;

        server = create(preferences, host, port, asker.wwwRoot, asker.dalDatabase);
        // server.setUseSimpleDatabase(asker.useSimpleDatabase);
    }

    final DalServer f_server = server;
    final File f_wwwRoot = docRoot;
    final Image f_serverIconImage = serverIconImage;

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            DalServerFactory factory = new DalServerFactory() {
                @Override
                public DalServer create(String hostName, int port, File wwwRoot, DalDatabase dalDatabase) {
                    return DalServer.create(preferences, hostName, port, wwwRoot, dalDatabase);
                }
            };
            ServerGui gui = new ServerGui(f_serverIconImage, f_server, factory, f_wwwRoot, preferences);
            gui.setVisible(true);
        }
    });

}

From source file:Main.java

public static int getWidthFromImage(String filename) {
    BufferedImage image;/*from www .j a  va2  s .co  m*/
    try {
        image = ImageIO.read(new File(filename));
        return image.getWidth();
    } catch (IOException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
    return -1;
}

From source file:Main.java

public static ImageIcon GetIconFromURL(String url) {
    BufferedImage image;//from   w  w  w .j  a va  2  s .  c om
    try {
        image = ImageIO.read(new URL(url));
    } catch (Exception e) {
        return new ImageIcon();
    }
    return new ImageIcon(image);
}

From source file:Main.java

public static BufferedImage getImageFromFile(File f) {
    BufferedImage img = null;//from w ww.j  a  v a  2s.  c  om
    try {
        img = ImageIO.read(f);
    } catch (IOException e) {
        // if failed, then copy it to local path for later check:TBD
        // FileUtils.copyFile(f, new File(p1));
        e.printStackTrace();
        System.exit(1);
    }
    return img;
}

From source file:Main.java

public static BufferedImage getBufferImage(String path) throws IOException {
    File file = new File(path);
    return ImageIO.read(file);
}

From source file:Main.java

public static String getImageDimension(String imgLocation) throws Exception {
    BufferedImage image = null;//  w w  w. j  a  v  a  2 s  .com
    try {
        image = ImageIO.read(new URL(imgLocation));
    } catch (Exception e) {
        // If an error occurs, we consider the image as null. - FB
    }
    return (image == null ? "-1,-1" : image.getWidth() + "," + image.getHeight());
}

From source file:Main.java

public static byte[] getCompressedImage(byte[] rgb) {

    BufferedImage image;/*from w  ww  . j  av a2s . c o  m*/
    int width;
    int height;

    try {
        image = ImageIO.read(new ByteArrayInputStream(rgb));
        width = image.getWidth();
        height = image.getHeight();

        for (int i = 0; i < height; i++) {

            for (int j = 0; j < width; j++) {

                Color c = new Color(image.getRGB(j, i));
                int red = (int) (c.getRed() * 0.299);
                int green = (int) (c.getGreen() * 0.587);
                int blue = (int) (c.getBlue() * 0.114);
                Color newColor = new Color(red + green + blue,

                        red + green + blue, red + green + blue);

                image.setRGB(j, i, newColor.getRGB());
            }
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", baos);
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        baos.close();

        return imageInByte;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}