Example usage for javax.imageio.stream FileImageOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

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

/**
 * Crop Image/*from w ww. ja  v  a2 s .  c  o  m*/
 * @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;
}

From source file:com.mycompany.CRMFly.ManagedBeans.EmployeeBean.java

public void handleFileUpload(FileUploadEvent event) {
    // UploadedFile file = event.getFile();
    setUploaded_image(event.getFile());/*w w  w . j  a  va  2s.  c  om*/
    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();
    String v_file_ext = getUploaded_image().getFileName()
            .split("\\.")[(getUploaded_image().getFileName().split("\\.").length) - 1];
    setUpload_location(servletContext.getRealPath("") + File.separator + "temp-images" + File.separator + "3"
            + "." + v_file_ext);
    FileImageOutputStream imageOutput;
    try {
        imageOutput = new FileImageOutputStream(new File(getUpload_location()));
        imageOutput.write(getUploaded_image().getContents(), 0, getUploaded_image().getContents().length);
        imageOutput.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    byte[] file = new byte[uploaded_image.getContents().length];
    System.arraycopy(uploaded_image.getContents(), 0, file, 0, uploaded_image.getContents().length);
    employee.setPhoto(file);

    FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, msg);
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void saveJPG(BufferedImage img, File file) {
    ImageWriter writer = null;/*from  ww  w.  j  a  va 2  s . c o m*/
    FileImageOutputStream output = null;
    try {
        writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(1);
        output = new FileImageOutputStream(file);
        writer.setOutput(output);
        IIOImage iioImage = new IIOImage(img, null, null);
        writer.write(null, iioImage, param);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            if (writer != null) {
                writer.dispose();
            }
            if (output != null) {
                output.close();
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}

From source file:org.yamj.core.service.file.FileStorageService.java

public void storeImage(String filename, StorageType type, BufferedImage bi, ImageFormat imageFormat,
        int quality) throws Exception {
    LOG.debug("Store {} {} image: {}", type, imageFormat, filename);
    String storageFileName = getStorageName(type, filename);
    File outputFile = new File(storageFileName);

    ImageWriter writer = null;/*from  www .j  a v  a2 s .co  m*/
    FileImageOutputStream output = null;
    try {
        if (ImageFormat.PNG == imageFormat) {
            ImageIO.write(bi, "png", outputFile);
        } else {
            float jpegQuality = (float) quality / 100;
            BufferedImage bufImage = new BufferedImage(bi.getWidth(), bi.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
            bufImage.createGraphics().drawImage(bi, 0, 0, null, null);

            @SuppressWarnings("rawtypes")
            Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
            writer = (ImageWriter) iter.next();

            ImageWriteParam iwp = writer.getDefaultWriteParam();
            iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            iwp.setCompressionQuality(jpegQuality);

            output = new FileImageOutputStream(outputFile);
            writer.setOutput(output);
            IIOImage image = new IIOImage(bufImage, null, null);
            writer.write(null, image, iwp);
        }
    } finally {
        if (writer != null) {
            writer.dispose();
        }
        if (output != null) {
            try {
                output.close();
            } catch (IOException ex) {
                LOG.trace("Failed to close stream: {}", ex.getMessage(), ex);
            }
        }
    }
}

From source file:net.intelliant.util.UtilCommon.java

private static String generateCompressedImageForInputFile(String locationInFileSystem, String srcFileName)
        throws NoSuchAlgorithmException, IOException {
    String outputFileName = srcFileName;
    File srcFile = new File(locationInFileSystem, srcFileName);
    File compressedFile = null;//from  w  ww . j a va2 s . co  m
    FileImageOutputStream outputStream = null;
    try {
        if (srcFile.exists()) {
            String md5sum = getMD5SumForFile(srcFile.getAbsolutePath());
            int extentionIndex = srcFileName.lastIndexOf("."); // find index of extension.
            if (extentionIndex != -1) {
                outputFileName = outputFileName.replaceFirst("\\.", "_" + md5sum + ".");
            }
            compressedFile = new File(locationInFileSystem, outputFileName);
            if (Debug.infoOn()) {
                Debug.logInfo("[generateCompressedImageFor] sourceFile >> " + srcFile.getAbsolutePath(),
                        module);
                Debug.logInfo("[generateCompressedImageFor] md5sum >> " + md5sum, module);
                Debug.logInfo(
                        "[generateCompressedImageFor] compressedFile >> " + compressedFile.getAbsolutePath(),
                        module);
            }
            if (!compressedFile.exists()) {
                if (Debug.infoOn()) {
                    Debug.logInfo("[generateCompressedImageFor] compressed file does NOT exist..", module);
                }
                Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
                ImageWriter imageWriter = (ImageWriter) iter.next();
                ImageWriteParam iwp = imageWriter.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality(Float.parseFloat(imageCompressionQuality)); // an integer between 0 and 1, 1 specifies minimum compression and maximum quality
                BufferedImage bufferedImage = ImageIO.read(srcFile);
                outputStream = new FileImageOutputStream(compressedFile);
                imageWriter.setOutput(outputStream);
                IIOImage image = new IIOImage(bufferedImage, null, null);
                imageWriter.write(null, image, iwp);
            } else {
                if (Debug.infoOn()) {
                    Debug.logInfo(
                            "[generateCompressedImageFor] compressed file exists, not compressing again..",
                            module);
                }
            }
        } else {
            Debug.logWarning(String.format("Source image file does NOT exist..", srcFile), module);
        }
    } finally {
        if (outputStream != null) {
            outputStream.close();
            outputStream = null;
        }
    }
    return outputFileName;
}

From source file:de.hpi.fgis.hdrs.node.Node.java

private void writeSegmentIdCounter() {
    try {/*www. java2  s .com*/
        File f = new File(rootDir.getAbsolutePath() + File.separator + SEGMENT_ID_COUNTER_FILE);
        if (f.isFile()) {
            if (!f.delete()) {
                throw new IOException("Cannot delete old index meta file");
            }
        }
        FileImageOutputStream out = new FileImageOutputStream(f);
        out.writeInt(segmentIdCounter);
        out.close();
    } catch (IOException ex) {
        LOG.error("Error writing store meta file", ex);
    }
}

From source file:com.lynk.hrm.ui.dialog.InfoEmployee.java

private void updateData() {
    uiId.setText(employee.getId());/*w  w  w  .  j  a v a 2  s. co m*/
    uiName.setText(employee.getName());
    uiNamePy.setText(employee.getNamePy());
    if (StringUtils.isNotEmpty(employee.getState())) {
        uiState.setSelectedItem(employee.getState());
        switch (employee.getState()) {
        case Employee.STATE_LEAVE:
        case Employee.STATE_RETIRE:
        case Employee.STATE_DELETE:
            uiInfoTab.setSelectedIndex(1);
            break;
        case Employee.STATE_SUSPEND:
            uiInfoTab.setSelectedIndex(2);
            break;
        case Employee.STATE_PROBATION:
        case Employee.STATE_CONTRACT:
        default:
            break;
        }
    }
    uiTimeCardLeaveCertify.setText(employee.getTimeCard());
    uiIdCard.setText(employee.getIdCard());
    uiBirthday.setText(employee.getBirthday());
    uiAge.setText(employee.getAge().toString());
    uiGender.setText(employee.getGender());
    if (StringUtils.isNotEmpty(employee.getMaritalStatus())) {
        uiMarital.setSelectedItem(employee.getMaritalStatus());
    }
    uiContact.setText(employee.getContact());
    if (StringUtils.isNotEmpty(employee.getCensus())) {
        uiCensus.setSelectedItem(employee.getCensus());
    }
    uiCensusAddress.setText(employee.getCensusAddress());

    // ?
    if (employee.getEmployeePhoto() != null && employee.getEmployeePhoto().getPhoto() != null
            && employee.getEmployeePhoto().getPhoto().length > 0) {
        EmployeePhoto photo = employee.getEmployeePhoto();
        try {
            File imageFile = new File(System.getProperty("user.dir") + "/temp/" + employee.getId() + ".png");
            FileImageOutputStream fios = new FileImageOutputStream(imageFile);
            fios.write(photo.getPhoto());
            fios.flush();
            fios.close();
            uiPhoto.putClientProperty("path", imageFile.getPath());
            uiPhoto.setImage(imageFile.getPath());
        } catch (Exception e) {
            showErrorMsg(e);
        }
    } else {
        uiPhoto.setImage("resource/image/default_emp_photo.png", true);
    }

    uiAddress.setText(employee.getAddress());
    if (StringUtils.isNotEmpty(employee.getCensusProvince())) {
        uiResidencePermit.setSelectedItem(employee.getCensusProvince());
    }
    if (StringUtils.isNotEmpty(employee.getDept())) {
        uiDept.setText(employee.getDept());
    }
    if (StringUtils.isNotEmpty(employee.getJob())) {
        uiJob.setText(employee.getJob());
    }
    if (StringUtils.isNotEmpty(employee.getEntryDate())) {
        uiEntryDate.setDate(Utils.dateFromStr(employee.getEntryDate()));
    }
    uiWorkAge.setText(UtilsClient.convertWorkAgeToStr(employee.getWorkAge()));
    if (StringUtils.isNotEmpty(employee.getProbationDate())) {
        uiProbation.setDate(Utils.dateFromStr(employee.getProbationDate()));
    }
    if (StringUtils.isNotEmpty(employee.getExpirationDate())) {
        uiExpiration.setText(employee.getExpirationDate());
    }
    if (StringUtils.isNotEmpty(employee.getDegree())) {
        uiDegree.setSelectedItem(employee.getDegree());
    }
    uiSchool.setText(employee.getSchool());
    uiMajor.setText(employee.getMajor());
    //      uiSuspendEnd.setText(employee.getSuspendEnd());
    uiWorkExperience.setText(employee.getWorkExperience());
    uiSocialCard.setText(employee.getSocialCard());
    uiHousingCard.setText(employee.getHousingCard());
    uiBankCard.setText(employee.getBankCard());
    uiNote.setText(employee.getNote());
    uiPerformance.setText(employee.getCensusCity());
    if (StringUtils.isNotEmpty(employee.getLeaveDate())) {
        uiLeaveDate.setDate(Utils.dateFromStr(employee.getLeaveDate()));
    }

    if (StringUtils.isNotEmpty(employee.getSocialEndDate())) {
        uiSocialEndDate.setText(employee.getSocialEndDate());
    }
    if (StringUtils.isNotEmpty(employee.getHousingEndDate())) {
        uiHousingEndDate.setText(employee.getHousingEndDate());
    }
    uiLeaveType.setSelectedItem(employee.getLeaveType());
    uiLeaveReason.setText(employee.getLeaveReason());
    uiFactory.setSelectedItem(employee.getSuspendNote());
    uiDdg.setSelectedItem(employee.getSuspendStart());
}

From source file:com.lynk.hrm.ui.dialog.InfoEmployee.java

private void initData(final String id) {
    showWaitPanel("?......");
    new SwingWorker<Employee, Void>() {

        @Override//from   w  ww . j  a va2 s  .c  o m
        protected Employee doInBackground() throws Exception {
            if (StringUtils.isEmpty(id)) {
                return Employee.createNewEmployee();
            } else {
                return HrmBiz.getInstance().getEmployee(id);
            }
        }

        @Override
        protected void done() {
            try {
                employee = get();
                uiEntryDate.setCalendar(Calendar.getInstance());
                uiId.setText(employee.getId());
                uiName.setText(employee.getName());
                uiNamePy.setText(employee.getNamePy());
                if (StringUtils.isNotEmpty(employee.getState())) {
                    uiState.setSelectedItem(employee.getState());
                    switch (employee.getState()) {
                    case Employee.STATE_LEAVE:
                    case Employee.STATE_RETIRE:
                    case Employee.STATE_DELETE:
                        uiInfoTab.setSelectedIndex(1);
                        break;
                    case Employee.STATE_SUSPEND:
                        uiInfoTab.setSelectedIndex(2);
                        break;
                    case Employee.STATE_PROBATION:
                    case Employee.STATE_CONTRACT:
                    default:
                        break;
                    }
                }
                uiTimeCardLeaveCertify.setText(employee.getTimeCard());
                uiIdCard.setText(employee.getIdCard());
                uiBirthday.setText(employee.getBirthday());
                uiAge.setText(employee.getAge().toString());
                uiGender.setText(employee.getGender());
                if (StringUtils.isNotEmpty(employee.getMaritalStatus())) {
                    uiMarital.setSelectedItem(employee.getMaritalStatus());
                }
                uiContact.setText(employee.getContact());
                if (StringUtils.isNotEmpty(employee.getCensus())) {
                    uiCensus.setSelectedItem(employee.getCensus());
                }
                uiCensusAddress.setText(employee.getCensusAddress());

                // ?
                if (employee.getEmployeePhoto() != null && employee.getEmployeePhoto().getPhoto() != null
                        && employee.getEmployeePhoto().getPhoto().length > 0) {
                    EmployeePhoto photo = employee.getEmployeePhoto();
                    uiPhoto.putClientProperty("photo", employee.getEmployeePhoto().getPhoto());
                    try {
                        File imageFile = new File(
                                System.getProperty("user.dir") + "/temp/" + employee.getId() + ".png");
                        FileImageOutputStream fios = new FileImageOutputStream(imageFile);
                        fios.write(photo.getPhoto());
                        fios.flush();
                        fios.close();
                        uiPhoto.putClientProperty("path", imageFile.getPath());
                        uiPhoto.setImage(imageFile.getPath());
                    } catch (Exception e) {
                        showErrorMsg(e);
                    }
                } else {
                    uiPhoto.setImage("resource/image/default_emp_photo.png", true);
                }

                uiAddress.setText(employee.getAddress());
                if (StringUtils.isNotEmpty(employee.getCensusProvince())) {
                    uiResidencePermit.setSelectedItem(employee.getCensusProvince());
                }
                if (StringUtils.isNotEmpty(employee.getSuspendNote())) {
                    uiFactory.setSelectedItem(employee.getSuspendNote());
                }
                if (StringUtils.isNotEmpty(employee.getDept())) {
                    uiDept.setText(employee.getDept());
                }
                if (StringUtils.isNotEmpty(employee.getJob())) {
                    uiJob.setText(employee.getJob());
                }
                if (StringUtils.isNotEmpty(employee.getSuspendStart())) {
                    uiDdg.setSelectedItem(employee.getSuspendStart());
                }
                if (StringUtils.isNotEmpty(employee.getEntryDate())) {
                    uiEntryDate.setDate(Utils.dateFromStr(employee.getEntryDate()));
                }
                uiWorkAge.setText(UtilsClient.convertWorkAgeToStr(employee.getWorkAge()));
                if (StringUtils.isNotEmpty(employee.getProbationDate())) {
                    uiProbation.setDate(Utils.dateFromStr(employee.getProbationDate()));
                }
                if (StringUtils.isNotEmpty(employee.getExpirationDate())) {
                    uiExpiration.setText(employee.getExpirationDate());
                }
                if (StringUtils.isNotEmpty(employee.getDegree())) {
                    uiDegree.setSelectedItem(employee.getDegree());
                }
                uiSchool.setText(employee.getSchool());
                uiMajor.setText(employee.getMajor());
                uiWorkExperience.setText(employee.getWorkExperience());
                //               uiSuspendEnd.setText(employee.getSuspendEnd());
                uiSocialCard.setText(employee.getSocialCard());
                uiHousingCard.setText(employee.getHousingCard());
                uiBankCard.setText(employee.getBankCard());
                uiNote.setText(employee.getNote());
                uiPerformance.setText(employee.getCensusCity());
                uiPhoneShort.setText(employee.getPhoneShort());
                if (StringUtils.isNotEmpty(employee.getLeaveDate())) {
                    uiLeaveDate.setDate(Utils.dateFromStr(employee.getLeaveDate()));
                }

                if (StringUtils.isNotEmpty(employee.getSocialEndDate())) {
                    uiSocialEndDate.setText(employee.getSocialEndDate());
                }
                if (StringUtils.isNotEmpty(employee.getHousingEndDate())) {
                    uiHousingEndDate.setText(employee.getHousingEndDate());
                }
                uiLeaveType.setSelectedItem(employee.getLeaveType());
                uiLeaveReason.setText(employee.getLeaveReason());
                if (StringUtils.isNotEmpty(employee.getJobTitle())) {
                    uiGuide.setText(employee.getJobTitle());
                }
                hideWaitPanel();
            } catch (Exception e) {
                hideWaitPanel();
                showErrorMsg(e);
            }

        }

    }.execute();
}

From source file:org.angcms.util.ResourceUtils.java

public static String createImage_(String folder, String imageFileName, byte[] data) {
    try {//from  w  w  w .j a  va2s.c om
        String actualFileName = getUniqueName(getRealPath(folder), imageFileName);
        FileImageOutputStream imageOutput;
        imageOutput = new FileImageOutputStream(new File(actualFileName));
        imageOutput.write(data, 0, data.length);
        imageOutput.close();
        return actualFileName.substring(actualFileName.lastIndexOf(File.separator) + 1);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.dcm4che2.tool.dcm2dcm.Dcm2Dcm.java

/**
 * Recodes the images from the source transfer syntax, as read from the src
 * file, to the specified destination syntax.
 *//*from   ww w .  j ava2  s  .co m*/
public void recodeImages(File src, File dest) throws IOException {
    ImageReader reader = new DicomImageReaderSpi().createReaderInstance();
    ImageWriter writer = new DicomImageWriterSpi().createWriterInstance();

    DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null);

    DicomObject ds;
    int frames;

    FileImageOutputStream output = null;

    try {
        FileImageInputStream input = new FileImageInputStream(src);

        try {
            reader.setInput(input);
            if (dest.exists())
                dest.delete();
            output = new FileImageOutputStream(dest);
            writer.setOutput(output);
            DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata();
            ds = streamMeta.getDicomObject();

            DicomObject newDs = new BasicDicomObject();
            ds.copyTo(newDs);
            writeMeta.setDicomObject(newDs);
            frames = ds.getInt(Tag.NumberOfFrames, 1);
            newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid());
            newDs.putString(Tag.ImplementationClassUID, VR.UI, Implementation.classUID());
            newDs.putString(Tag.ImplementationVersionName, VR.SH, Implementation.versionName());
            if (overwriteObject != null) {
                overwriteObject.copyTo(newDs);
            }
        } finally {
            reader.dispose();
        }
        writer.prepareWriteSequence(writeMeta);
        for (int i = 0; i < frames; i++) {
            FileInputStream inputStream = new FileInputStream(src);
            try {
                WritableRaster r = (WritableRaster) readRaster(inputStream, i);

                ColorModel cm = ColorModelFactory.createColorModel(ds);
                BufferedImage bi = new BufferedImage(cm, r, false, null);
                IIOImage iioimage = new IIOImage(bi, null, null);
                writer.writeToSequence(iioimage, null);
            } catch (NoSuchFieldException ex) {
                System.err.println(ex.toString());
            } catch (IllegalAccessException ex) {
                System.err.println(ex.toString());
            } finally {
                inputStream.close();
            }
        }
        writer.endWriteSequence();
    } finally {
        if (output != null) {
            output.close();
        }
    }
}