Example usage for javax.imageio.stream FileImageOutputStream FileImageOutputStream

List of usage examples for javax.imageio.stream FileImageOutputStream FileImageOutputStream

Introduction

In this page you can find the example usage for javax.imageio.stream FileImageOutputStream FileImageOutputStream.

Prototype

public FileImageOutputStream(RandomAccessFile raf) 

Source Link

Document

Constructs a FileImageOutputStream that will write to a given RandomAccessFile .

Usage

From source file:com.tropicscrum.frontend.controllers.request.RegisterRequestBean.java

public String registerUser() {
    try {//from w  w w  .ja v a2 s .  c o  m
        registerViewBean.getUser()
                .setPassword(md5Converter.StringToMD5(registerViewBean.getUser().getPassword()));
        if (registerViewBean.getUser().getAvatar() == null) {
            registerViewBean.getUser().setAvatar("/images/default-user.png");
        }
        if (!registerViewBean.getUser().getAvatar().equals("/images/default-user.png")) {
            if (registerViewBean.getCroppedImage() != null) {
                final Properties settingsProps = new Properties();
                settingsProps.load(getClass().getResourceAsStream("/settings.properties"));
                String path = "/" + settingsProps.getProperty("staticPath")
                        + registerViewBean.getUser().getAvatar();
                try (FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path))) {
                    imageOutput.write(registerViewBean.getCroppedImage().getBytes(), 0,
                            registerViewBean.getCroppedImage().getBytes().length);
                }
            }
        }
        registerViewBean.setUser(userFacadeRemote.create(registerViewBean.getUser()));
        String encodedId = Base64.encodeToString(registerViewBean.getUser().getId().toString().getBytes(),
                true);
        RequestDomain requestDomain = new RequestDomain();
        FacesContext context = FacesContext.getCurrentInstance();
        InputStream input = new URL(requestDomain.getApplicationPath(context)
                + "/template/email/confirmEmail.xhtml?id=" + encodedId).openStream();
        String result = IOUtils.toString(input, StandardCharsets.UTF_8);
        userFacadeRemote.sendConfirmEmail(registerViewBean.getUser(), result);
    } catch (NoSuchAlgorithmException | IOException e) {
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_FATAL, "Error", "No se pudo registrar el usuario"));
    }

    return "thanks_register?faces-redirect=true";

}

From source file:com.bc.util.io.FileUtils.java

public static void copy(File source, File target) throws IOException {
    final byte[] buffer = new byte[ONE_KB * ONE_KB];
    int bytesRead;

    FileImageInputStream sourceStream = null;
    FileImageOutputStream targetStream = null;

    try {//  w w  w.  j  a v  a  2 s .c  om
        final File targetDir = target.getParentFile();
        if (!targetDir.isDirectory()) {
            if (!targetDir.mkdirs()) {
                throw new IOException("failed to create target directory: " + targetDir.getAbsolutePath());
            }
        }
        target.createNewFile();

        sourceStream = new FileImageInputStream(source);
        targetStream = new FileImageOutputStream(target);
        while ((bytesRead = sourceStream.read(buffer)) >= 0) {
            targetStream.write(buffer, 0, bytesRead);
        }
    } finally {
        if (sourceStream != null) {
            sourceStream.close();
        }
        if (targetStream != null) {
            targetStream.flush();
            targetStream.close();
        }
    }
}

From source file:beans.FotoBean.java

public void tirarFoto(CaptureEvent captureEvent) throws IOException {
    arquivo = gerarNome();//from   w  w w .  j a  v  a  2 s  . co m
    byte[] data = captureEvent.getData();

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();
    String pasta = servletContext.getRealPath("") + File.separator + "resources" + File.separator
            + "fotossalvas";
    File vpasta = new File(pasta);
    if (!vpasta.exists()) {
        vpasta.setWritable(true);
        vpasta.mkdirs();
    }
    String novoarquivo = pasta + File.separator + arquivo + ".jpeg";
    System.out.println(novoarquivo);
    fotosalva = new File(novoarquivo);
    fotosalva.createNewFile();
    FileImageOutputStream imageOutput;
    try {
        imageOutput = new FileImageOutputStream(fotosalva);
        imageOutput.write(data, 0, data.length);
        imageOutput.close();

    } catch (IOException e) {
        Util.criarMensagemErro(e.toString());

    }
}

From source file:com.kahlon.guard.controller.PersonImageManager.java

/**
 * Upload person image file//from  w  w  w  .ja  v  a2  s .  co m
 *
 * @param event
 * @throws java.io.IOException
 */
public void onUpload(FileUploadEvent event) throws IOException {
    photo = getRandomImageName();
    byte[] data = IOUtils.toByteArray(event.getFile().getInputstream());

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();
    String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator
            + "image" + File.separator + "temp" + File.separator + photo + ".png";
    if (fileNames == null) {
        fileNames = new ArrayList<>();
    }
    fileNames.add(newFileName);

    FileImageOutputStream imageOutput;
    try {
        imageOutput = new FileImageOutputStream(new File(newFileName));
        imageOutput.write(data, 0, data.length);
        imageOutput.close();

        BufferedImage originalImage = ImageIO.read(new File(newFileName));
        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

        BufferedImage resizeImagePng = resizeImageWithHint(originalImage, type);
        ImageIO.write(resizeImagePng, "png", new File(newFileName));

    } catch (Exception e) {
        throw new FacesException("Error in writing captured image.");
    }
    FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, msg);
    imageUpload = false;
}

From source file:edu.ku.brc.specify.extras.FishBaseInfoGetter.java

/**
 * Performs a "generic" HTTP request and fill member variable with results use
 * "getDigirResultsetStr" to get the results as a String
 *
 *//*from  w w  w  . j a  v a 2  s  . c om*/
public Image getImage(final String fileName, final String url) {
    imageURL = url;

    String fullPath = tmpDir + File.separator + fileName;
    ////System.out.println(fullPath);
    File file = new File(fullPath);
    if (file.exists()) {
        try {
            return new ImageIcon(fullPath).getImage();

        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FishBaseInfoGetter.class, ex);
            ex.printStackTrace();
            status = ErrorCode.Error;
        }

    } else {
        byte[] bytes = super.doHTTPRequest(url);

        try {
            FileImageOutputStream fos = new FileImageOutputStream(file);
            fos.write(bytes);
            fos.flush();
            fos.close();

            return new ImageIcon(bytes).getImage();

        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(FishBaseInfoGetter.class, ex);
            ex.printStackTrace();
            status = ErrorCode.Error;
        }
    }
    return null;
}

From source file:com.actelion.research.orbit.imageAnalysis.utils.ImageUtils.java

/**
 * Stores BufferedImage as JPEG2000 encoded file.
 *
 * @param bi//from  w  w w.  j  av  a 2  s .  c o  m
 * @param filename
 * @param dEncRate
 * @param lossless
 * @throws IOException
 */
public static void storeBIAsJP2File(BufferedImage bi, String filename, double dEncRate, boolean lossless)
        throws IOException {

    if (hasJPEG2000FileTag(filename)) {

        IIOImage iioImage = new IIOImage(bi, null, null);

        ImageWriter jp2iw = ImageIO.getImageWritersBySuffix("jp2").next();
        J2KImageWriteParam writeParam = (J2KImageWriteParam) jp2iw.getDefaultWriteParam();

        // Indicates using the lossless scheme or not. It is equivalent to use reversible quantization and 5x3 integer wavelet filters. The default is true.
        writeParam.setLossless(lossless);

        if (lossless)
            writeParam.setFilter(J2KImageWriteParam.FILTER_53); // Specifies which wavelet filters to use for the specified tile-components. JPEG 2000 part I only supports w5x3 and w9x7 filters.
        else
            writeParam.setFilter(J2KImageWriteParam.FILTER_97);

        if (!lossless) {
            // The bitrate in bits-per-pixel for encoding. Should be set when lossy compression scheme is used. With the default value Double.MAX_VALUE, a lossless compression will be done.
            writeParam.setEncodingRate(dEncRate);

            // changes in compression rate are done in the following way
            // however JPEG2000 implementation seems not to support this <-- no differences visible
            //                writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            //                writeParam.setCompressionType(writeParam.getCompressionTypes()[0]);
            //                writeParam.setCompressionQuality(1.0f);
        }

        ImageOutputStream ios = null;
        try {
            ios = new FileImageOutputStream(new File(filename));
            jp2iw.setOutput(ios);
            jp2iw.write(null, iioImage, writeParam);
            jp2iw.dispose();
            ios.flush();
        } finally {
            if (ios != null)
                ios.close();
        }
    } else
        System.err.println("please name your file as valid JPEG2000 file: ends with .jp2");
}

From source file:com.kahlon.guard.controller.PersonImageManager.java

/**
 * Capture Image/*w  ww  .j ava 2  s . c o m*/
 * 
 * @param captureEvent
 */
public void onCapture(CaptureEvent captureEvent) {

    photo = getRandomImageName();
    byte[] data = captureEvent.getData();

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();
    String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator
            + "image" + File.separator + "temp" + File.separator + photo + ".png";
    if (fileNames == null) {
        fileNames = new ArrayList<>();
    }
    fileNames.add(newFileName);

    FileImageOutputStream imageOutput;
    try {
        imageOutput = new FileImageOutputStream(new File(newFileName));
        imageOutput.write(data, 0, data.length);
        imageOutput.close();
        imageUpload = false;
    } catch (Exception e) {
        throw new FacesException("Error in writing captured image.");
    }
}

From source file:de.bamamoto.mactools.png2icns.Scaler.java

public static void save(BufferedImage image, String filename) throws IOException {
    Iterator writers = ImageIO.getImageWritersByFormatName("PNG");
    if (writers.hasNext()) {
        ImageWriter imageWriter = (ImageWriter) writers.next();
        ImageWriteParam params = imageWriter.getDefaultWriteParam();

        File outFile = new File(filename);
        try (FileImageOutputStream output = new FileImageOutputStream(outFile)) {
            imageWriter.setOutput(output);
            IIOImage outImage = new IIOImage(image, null, null);
            imageWriter.write(null, outImage, params);
        }/*from  www.ja v a  2 s.  c  om*/
    }
}

From source file:editeurpanovisu.ReadWriteImage.java

/**
 *
 * @param img//ww w.j  a  v  a2  s  . c om
 * @param destFile
 * @param quality
 * @param sharpen
 * @param sharpenLevel
 * @throws IOException
 */
public static void writeJpeg(Image img, String destFile, float quality, boolean sharpen, float sharpenLevel)
        throws IOException {
    sharpenMatrix = calculeSharpenMatrix(sharpenLevel);
    BufferedImage imageRGBSharpen = null;
    IIOImage iioImage = null;
    BufferedImage image = SwingFXUtils.fromFXImage(img, null); // Get buffered image.

    BufferedImage imageRGB = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.OPAQUE); // Remove alpha-channel from buffered image.

    Graphics2D graphics = imageRGB.createGraphics();
    graphics.drawImage(image, 0, 0, null);
    if (sharpen) {
        imageRGBSharpen = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Kernel kernel = new Kernel(3, 3, sharpenMatrix);
        ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        cop.filter(imageRGB, imageRGBSharpen);
    }
    ImageWriter writer = null;
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(quality);
        output = new FileImageOutputStream(new File(destFile));
        writer.setOutput(output);
        if (sharpen) {
            iioImage = new IIOImage(imageRGBSharpen, null, null);
        } else {
            iioImage = new IIOImage(imageRGB, null, null);
        }
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            output.close();
        }
    }
    graphics.dispose();
}

From source file:com.kahlon.guard.controller.PersonImageManager.java

/**
 * Crop Image//from   ww w .j  a va2  s  .  c  om
 * @return
 */
public String crop() {
    if (croppedImage == null) {
        return null;
    }

    setNewImageName(getRandomImageName());
    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();
    String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator
            + "image" + File.separator + "temp" + File.separator + getNewImageName() + ".png";
    if (fileNames == null) {
        fileNames = new ArrayList<>();
    }
    fileNames.add(newFileName);

    FileImageOutputStream imageOutput;
    try {
        imageOutput = new FileImageOutputStream(new File(newFileName));
        imageOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length);
        imageOutput.close();
    } catch (FileNotFoundException e) {
        throw new FacesException("File not found.", e.getCause());
    } catch (IOException e) {
        throw new FacesException("IO Exception found.", e.getCause());
    }

    return null;
}