Example usage for javax.imageio ImageReader setInput

List of usage examples for javax.imageio ImageReader setInput

Introduction

In this page you can find the example usage for javax.imageio ImageReader setInput.

Prototype

public void setInput(Object input, boolean seekForwardOnly) 

Source Link

Document

Sets the input source to use to the given ImageInputStream or other Object .

Usage

From source file:org.exoplatform.wcm.ext.component.activity.FileUIActivity.java

protected int getImageWidth(Node node) {
    int imageWidth = 0;
    try {//w  ww. ja  va  2  s  . c  o m
        if (node.hasNode(NodetypeConstant.JCR_CONTENT))
            node = node.getNode(NodetypeConstant.JCR_CONTENT);
        ImageReader reader = ImageIO.getImageReadersByMIMEType(mimeType).next();
        ImageInputStream iis = ImageIO.createImageInputStream(node.getProperty("jcr:data").getStream());
        reader.setInput(iis, true);
        imageWidth = reader.getWidth(0);
        iis.close();
        reader.dispose();
    } catch (Exception e) {
        LOG.info("Cannot get node");
    }
    return imageWidth;
}

From source file:org.exoplatform.wcm.ext.component.activity.FileUIActivity.java

protected int getImageHeight(Node node) {
    int imageHeight = 0;
    try {/*from  w ww. jav a 2s  .co m*/
        if (node.hasNode(NodetypeConstant.JCR_CONTENT))
            node = node.getNode(NodetypeConstant.JCR_CONTENT);
        ImageReader reader = ImageIO.getImageReadersByMIMEType(mimeType).next();
        ImageInputStream iis = ImageIO.createImageInputStream(node.getProperty("jcr:data").getStream());
        reader.setInput(iis, true);
        imageHeight = reader.getHeight(0);
        iis.close();
        reader.dispose();
    } catch (Exception e) {
        LOG.info("Cannot get node");
    }
    return imageHeight;
}

From source file:org.n52.v3d.terrainserver.profileservice.ProfileServlet.java

/**
 * bearbeitet HTTP-Get-Anfragen an das Servlet.<p>
 * @param pRequest HTTP-Anfrage-Objekt//www  .j a  v a 2 s. co m
 * @param pResponse HTTP-Antwort-Objekt
 * @throws ServletException
 * @throws IOException
 */
public void doGet(HttpServletRequest pRequest, HttpServletResponse pResponse)
        throws ServletException, IOException {
    T3dTimeList lTimeProt = new T3dTimeList(); // zur Protokollierung der Rechenzeiten
    lTimeProt.addTimeStamp("init");

    // Eindeutigen Temporrdatei-Rumpf fr aktuelle Anfrage festlegen:
    String lTmpName = "~" + (mCounter++) + "_" + new java.util.Date().getTime();

    try {
        // Request-Parameter holen:
        HttpRequestParams lReqParams = this.fetchRequestParameters(pRequest);
        String lRequest = (String) lReqParams.getParameterValue("REQUEST");
        VgLineString lDefLine = (VgLineString) lReqParams.getParameterValue("DEFLINE");
        String lSRS = (String) lReqParams.getParameterValue("SRS");
        String lFormat = (String) lReqParams.getParameterValue("FORMAT");
        int lWidth = ((Integer) lReqParams.getParameterValue("WIDTH")).intValue();
        int lHeight = ((Integer) lReqParams.getParameterValue("HEIGHT")).intValue();
        double lExaggeration = ((Double) lReqParams.getParameterValue("EXAGGERATION")).doubleValue(); // todo sinnvoll?
        //int lVisAdds = ((Integer) lReqParams.getParameterValue("VISADDS")).intValue();
        VgPoint lPoint = (VgPoint) lReqParams.getParameterValue("POINT");

        if (lRequest.equalsIgnoreCase("GetCapabilities")) {
            HttpStandardResponse response = new HttpStandardResponse();
            response.sendXMLFile(mCapabilitiesFile, pResponse); // todo: serverrun/Capabilities.xml einrichten und web.xml-Additions
            this.logGetCapabilitiesInfo(lTmpName, pRequest);
            return;
        }

        if (!(lRequest.equalsIgnoreCase("GetGraph") || lRequest.equalsIgnoreCase("GetElevation")))
            throw new T3dException("Illegal request type " + lRequest + "...");

        // Request-Parameter aufbereiten und Wertebereiche prfen:
        ParameterPreparer pp = new ParameterPreparer();
        lSRS = pp.prepareSRS(lSRS);
        lFormat = pp.prepareFORMAT(lFormat, lRequest);
        if (lRequest.equalsIgnoreCase("GetGraph")) {
            lWidth = pp.prepareWIDTH(lWidth);
            lHeight = pp.prepareHEIGHT(lHeight);
        }
        if (lRequest.equalsIgnoreCase("GetElevation")) {
            String str = "" + lPoint.getX() + "," + lPoint.getY()
                    + ",0.0," /* erster Eckpunkt = Interpolationspunkt */
                    + lPoint.getX() + "," + lPoint.getY() + ",0.0"; /* zweiter Eckpunkt als Hilfspunkt */
            lDefLine = new GmLineString(str);
            if (lPoint instanceof VgPoint) {
                lPoint.setSRS(lSRS);
            }
        }

        sLogger.debug("ProfileServlet (" + lTmpName + "): Received " + lRequest + " request.");
        lTimeProt.setFinished("init");

        // Hhenmodell berechnen (Gridding):
        lTimeProt.addTimeStamp("dem_access");
        final boolean lDebug = false; // todo: auf 'false' setzen
        if (lDebug)
            System.out.println("lDefLine = " + lDefLine);
        VgEnvelope lBBox = lDefLine.envelope();
        lBBox.setSRS(lSRS);
        lBBox = this.assureBBoxExtent(lBBox);
        if (lDebug)
            System.out.println("lBBox = " + lBBox);
        GmSimpleElevationGrid lTerrain = this.setUpTerrain(lBBox);
        if (lDebug) {
            System.out.println("lTerrain = " + lTerrain);
            System.out.println("lTerrain.envelope = " + lTerrain.getGeometry().envelope());
        }
        lTimeProt.setFinished("dem_access");

        // Profil generieren:
        lTimeProt.addTimeStamp("profile_generation");
        FltElevationGrid2Profile lProc = new FltElevationGrid2Profile();
        VgProfile lProfile = lProc.transform(lTerrain, lDefLine);
        lTimeProt.setFinished("profile_generation");

        if (lRequest.equalsIgnoreCase("GetGraph")) {
            // Ergebnisbild generieren:
            lTimeProt.addTimeStamp("rendering");
            IoProfileWriter lWriter = new IoProfileWriter("SVG"); // stets SVG generieren
            String lResFile = mWorkingDirectory + "/" + lTmpName + ".svg";
            lWriter.writeToFile(lProfile, lResFile);
            boolean lSendAsPngImage = false;
            String lResFilePng = "";
            if (lFormat.equalsIgnoreCase("image/png"))
                lSendAsPngImage = true;
            if (lSendAsPngImage) {
                PNGTranscoder lTranscoder = new PNGTranscoder();
                String lSvgURI = new File(lResFile).toURL().toString();
                TranscoderInput lInput = new TranscoderInput(lSvgURI);
                lResFilePng = mWorkingDirectory + "/" + lTmpName + ".png";
                OutputStream lOStream = new FileOutputStream(lResFilePng);
                TranscoderOutput lOutput = new TranscoderOutput(lOStream);
                lTranscoder.transcode(lInput, lOutput);
                lOStream.flush();
                lOStream.close();
            }
            lTimeProt.setFinished("rendering");

            // Ergebnisbild als Antwort senden:
            lTimeProt.addTimeStamp("send_response");
            if (!lSendAsPngImage) {
                pResponse.setContentType("image/svg+xml"); // MIME-Typ fr Antwort setzen
                BufferedReader lDatRead;
                try {
                    lDatRead = new BufferedReader(new FileReader(lResFile));
                } catch (FileNotFoundException e) {
                    throw new T3dException("Internal error while reading \"" + lResFile + "\".");
                }
                PrintWriter out = pResponse.getWriter(); // PrintWriter auf die Antwort aufsetzen
                String line = lDatRead.readLine();
                while (line != null) { // generierte Temporrdatei zeilenweise senden
                    out.println(line);
                    line = lDatRead.readLine();
                }
                lDatRead.close();
                out.flush();
                out.close();
            } else {
                // Bild senden (vgl. Code aus WebTerrainServlet:
                try {
                    File f = new File(lResFilePng);
                    ImageInputStream is = ImageIO.createImageInputStream(f);
                    Iterator iter = ImageIO.getImageReaders(is); // liefert PNG-ImageReader
                    ImageReader reader = (ImageReader) iter.next();
                    reader.setInput(is, true); // seek forward only?
                    BufferedImage lImage = reader.read(0);

                    OutputStream out = pResponse.getOutputStream();
                    ImageIO.setUseCache(false); // wichtig!
                    pResponse.setContentType(lFormat); // MIME-Typ fr Antwort setzen
                    String resExt = MimeTypeHelper.getFileExtension(lFormat);
                    try {
                        ImageIO.write(lImage, resExt, out); // resExt ist informaler Formatname...
                    } catch (Exception e) {
                        throw new T3dException("Did not finish PNG image send process. " + e.getMessage(), 103); // todo fehler-nr. prfen und in doku
                    }
                    is.close();
                    out.close();
                } catch (IOException e) {
                    throw new T3dException(
                            "An I/O exception occured. The servlet could not send an image reponse.", 106); // todo fehler-nr. prfen und in doku
                }
            }
            File fSvg = new File(lResFile);
            fSvg.delete();
            if (lSendAsPngImage) {
                File fPng = new File(lResFilePng);
                fPng.delete();
            }
            lTimeProt.setFinished("send_response");
        } else {
            if (lRequest.equalsIgnoreCase("GetElevation")) {
                lTimeProt.addTimeStamp("send_response");
                double x, y, z;
                try {
                    x = ((VgLineString) (lProfile.getGeometry())).getVertex(0).getX(); // = lPoint.getX()
                    y = ((VgLineString) (lProfile.getGeometry())).getVertex(0).getY(); // = lPoint.getY()
                    z = (lProfile.getTZPair(0))[1];
                } catch (Throwable e) {
                    throw new T3dException("No elevation information available.");
                }

                // Antwort senden:
                short lCase = 0;
                if (lFormat.equalsIgnoreCase("text/plain"))
                    lCase = 1;
                if (lFormat.equalsIgnoreCase("text/xml"))
                    lCase = 2;
                if (lFormat.equalsIgnoreCase("text/html"))
                    lCase = 3;
                if (lFormat.equalsIgnoreCase("text/comma-separated-values"))
                    lCase = 4;
                if (lCase <= 0)
                    throw new T3dException("Internal servlet error."); // Kann nicht auftreten
                pResponse.setContentType(lFormat); // MIME-Typ fr Antwort setzen
                PrintWriter out = pResponse.getWriter(); // PrintWriter auf die Antwort aufsetzen
                switch (lCase) {
                case 1:
                    out.println("Position:");
                    out.println("SRS: " + lPoint.getSRS()); // = lSRS
                    out.println("X = " + x);
                    out.println("Y = " + y);
                    out.println("");
                    out.println("Elevation = " + z);
                    break;
                case 2:
                    out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\" ?>");
                    out.println("<ServiceResponse>");
                    out.println("  <Position>");
                    out.println("    <SRS>" + lPoint.getSRS() + "</SRS>"); // = lSRS
                    out.println("    <X>" + x + "</X>");
                    out.println("    <Y>" + y + "</Y>");
                    out.println("  </Position>");
                    out.println("  <Elevation>" + z + "</Elevation>");
                    out.println("</ServiceResponse>");
                    break;
                case 3:
                    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
                    out.println("<html>");
                    out.println("<head>");
                    out.println("<title>52N terrainServer elevation information</title>");
                    out.println("<font face=\"Verdana, Arial, Helvetica\" size=1>");
                    out.println("<meta http-equiv=Content-Type content=\"text/html; charset=iso-8859-1\">");
                    out.println("<body text=#000000 bgColor=#ffffff leftMargin=0 topMargin=0>");
                    out.println("<table border=\"1\">");
                    out.println("<tr><td><b>Position:</b></td><td><br></td></tr>");
                    out.println("<tr><td>SRS:</td><td>" + lPoint.getSRS() + "</td></tr>"); // lPoint.getSRS() = lSRS
                    out.println("<tr><td>X:</td><td>" + x + "<td></tr>");
                    out.println("<tr><td>Y:</td><td>" + y + "<td></tr>");
                    out.println("<tr><td><b>Elevation:</b></td><td>" + z + "<td></tr>");
                    out.println("</table>");
                    out.println("</html>");
                    break;
                case 4:
                    out.println(z);
                    break;
                }
                out.flush();
                out.close();
                lTimeProt.setFinished("send_response");
            }
        }

        //String lOutputFormatInfo = lFormat + " (" + lWidth + "x" + lHeight + ")";
        if (lRequest.equalsIgnoreCase("GetGraph"))
            this.logGetGraphInfo(lTmpName, lTerrain, lDefLine, lTimeProt, pRequest,
                    lFormat /*lOutputFormatInfo*/);
        else {
            if (lRequest.equalsIgnoreCase("GetElevation"))
                this.logGetElevationInfo(lTmpName, lTerrain, lPoint, lTimeProt, pRequest, lFormat);
        }

        sLogger.debug("ProfileServlet (" + lTmpName + "): Duly finished execution.");
    } catch (Throwable e) {
        sLogger.debug("ProfileServlet (" + lTmpName + "): Aborting execution. Error: " + e.getMessage());

        HttpStandardResponse response = new HttpStandardResponse();
        try {
            response.sendException(e.getMessage(), pResponse);
        } catch (Throwable e2) {
            try {
                response.sendException(e.getMessage(), pResponse);
            } catch (Throwable e3) {
                System.out.println("ProfileServlet: FATAL ERROR - " + e3.getMessage());
            }
        }
        try {
            this.logErrorInfo(lTmpName, lTimeProt, pRequest, e);
        } catch (Throwable e2) {
            System.out.println("ProfileServlet: FATAL ERROR - " + e2.getMessage());
        }
    }
}

From source file:org.psystems.dicomweb.Dcm2Jpg.java

public void convert(File src, File dest) throws IOException {
    Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
    ImageReader reader = iter.next();
    DicomImageReadParam param = (DicomImageReadParam) reader.getDefaultReadParam();
    param.setWindowCenter(center);/*w w w . ja v  a  2 s  .  c  om*/
    param.setWindowWidth(width);
    param.setVoiLutFunction(vlutFct);
    param.setPresentationState(prState);
    param.setPValue2Gray(pval2gray);
    param.setAutoWindowing(autoWindowing);
    ImageInputStream iis = ImageIO.createImageInputStream(src);
    BufferedImage bi;
    OutputStream out = null;
    try {
        reader.setInput(iis, false);
        bi = reader.read(frame - 1, param);
        if (bi == null) {
            System.out.println("\nError: " + src + " - couldn't read!");
            return;
        }
        out = new BufferedOutputStream(new FileOutputStream(dest));
        JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out);
        enc.encode(bi);
    } finally {
        CloseUtils.safeClose(iis);
        CloseUtils.safeClose(out);
    }
    System.out.print('.');
}

From source file:org.psystems.dicom.daemon.Dcm2Jpg.java

public void convert(File src, File dest) throws IOException {
    Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
    ImageReader reader = iter.next();
    DicomImageReadParam param = (DicomImageReadParam) reader.getDefaultReadParam();
    param.setWindowCenter(center);/* w w w .  jav  a 2  s.  c o m*/
    param.setWindowWidth(width);
    param.setVoiLutFunction(vlutFct);
    param.setPresentationState(prState);
    param.setPValue2Gray(pval2gray);
    param.setAutoWindowing(autoWindowing);
    ImageInputStream iis = ImageIO.createImageInputStream(src);
    BufferedImage bi;
    OutputStream out = null;
    try {
        reader.setInput(iis, false);
        if (reader.getNumImages(false) <= 0) {
            System.out.println("\nError: " + src + " - Don't haven any images!");
            return;
        }
        //            System.out.println("!!! frame="+frame+" p="+reader.getNumImages(false));
        bi = reader.read(frame - 1, param);
        if (bi == null) {
            System.out.println("\nError: " + src + " - couldn't read!");
            return;
        }
        out = new BufferedOutputStream(new FileOutputStream(dest));
        JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out);
        enc.encode(bi);
    } finally {
        CloseUtils.safeClose(iis);
        CloseUtils.safeClose(out);
    }
    System.out.print('.');
}

From source file:org.dcm4che2.tool.dcm2jpg.Dcm2Jpg.java

public void convert(File src, File dest) throws IOException {
    Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
    ImageReader reader = iter.next();
    DicomImageReadParam param = (DicomImageReadParam) reader.getDefaultReadParam();
    param.setWindowCenter(center);//www .j a  va2 s .  c om
    param.setWindowWidth(width);
    param.setVoiLutFunction(vlutFct);
    param.setPresentationState(prState);
    param.setPValue2Gray(pval2gray);
    param.setAutoWindowing(autoWindowing);
    ImageInputStream iis = ImageIO.createImageInputStream(src);
    BufferedImage bi;
    try {
        reader.setInput(iis, false);
        bi = reader.read(frame - 1, param);
        if (bi == null) {
            System.out.println("\nError: " + src + " - couldn't read!");
            return;
        }
        if (imageWriterClassname == null) {
            encodeByJPEGEncoder(bi, dest);
        } else {
            encodeByImageIO(bi, dest);
        }
    } finally {
        CloseUtils.safeClose(iis);
    }
    System.out.print('.');
}

From source file:nl.b3p.imagetool.ImageTool.java

/**
 * Reads an image from an http input stream.
 *
 * @param method Apache HttpClient GetMethod object
 * @param mime String representing the mime type of the image.
 *
 * @return BufferedImage/*  w ww.j  av a 2s  .  c  o m*/
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method.">
public static BufferedImage readImage(InputStream is, String mime) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int bytesRead = 0;
    byte[] buffer = new byte[2048];
    while (bytesRead != -1) {
        bytesRead = is.read(buffer, 0, buffer.length);
        if (bytesRead > 0) {
            baos.write(buffer, 0, bytesRead);
        }
    }
    ImageReader ir = null;
    BufferedImage i = null;
    try {
        if (mime.indexOf(";") != -1) {
            mime = mime.substring(0, mime.indexOf(";"));
        }
        String mimeType = getMimeType(mime);

        /* TODO: Kijken waarom er geen mime type meer binnenkomt. Wellicht door de
         * HttpClient vernieuwing in kaartenbalie ? */
        if (mimeType == null) {
            mimeType = "image/png";
        }

        if (mimeType == null) {
            log.error("Response from server not understood (mime = " + mime + "): " + baos.toString());
            throw new Exception(
                    "Response from server not understood (mime = " + mime + "): " + baos.toString());
        }

        ir = getReader(mimeType);
        if (ir == null) {
            log.error("no reader available for imageformat: "
                    + mimeType.substring(mimeType.lastIndexOf("/") + 1));
            throw new Exception("no reader available for imageformat: "
                    + mimeType.substring(mimeType.lastIndexOf("/") + 1));
        }
        //TODO Make smarter.. Possibly faster... But keep reporting!
        ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray()));
        ir.setInput(stream, true);
        i = ir.read(0);
        //if image is a png, has no alpha and has a tRNS then make that color transparent.
        if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) {
            PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0);
            if (metadata.tRNS_present) {
                int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue);
                BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB);
                for (int x = 0; x < i.getWidth(); x++) {
                    for (int y = 0; y < i.getHeight(); y++) {
                        int rgb = i.getRGB(x, y);
                        rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb;
                        tmp.setRGB(x, y, rgb);
                    }
                }
                i = tmp;
            }
        }
    } finally {
        if (ir != null) {
            ir.dispose();
        }
    }
    return i;
}

From source file:net.naijatek.myalumni.modules.members.presentation.action.MaintainMemberAction.java

public ActionForward updateMemberAvatar(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    ActionMessages errors = new ActionMessages();
    String fileTypes = SystemConfigConstants.CONTENT_TYPE;
    String avatarDir = getSysProp().getValue("AVATAR.FILEPATH");
    MyAlumniUserContainer continer = getUserContainer(request);

    int maxFileSize = 0;
    int maxHeight = 0;
    int maxWidth = 0;
    String overwrite = "false";

    if (isCancelled(request)) {
        return mapping.findForward(BaseConstants.FWD_CANCEL);
    }//from   www . j a  v a 2s .co  m

    MemberVO token = getCurrentLoggedInUser(request);
    MemberForm memberForm = (MemberForm) form;

    if (!memberSecurityCheck(request, token)) {
        return mapping.findForward(BaseConstants.FWD_LOGIN);
    }

    //  Set Max Size
    try {
        maxFileSize = Integer.parseInt(getAppProp().getValue("avatar.image.size").trim());
    } catch (Exception e) {
        maxFileSize = 120000; // 120000 Bytes  = 120 KB
    }

    // Set Max Height
    try {
        maxHeight = Integer.parseInt(getAppProp().getValue("avatar.image.height").trim());
    } catch (Exception e) {
        maxHeight = 200; // 200 px 
    }

    // Set Max Width
    try {
        maxWidth = Integer.parseInt(getAppProp().getValue("avatar.image.width").trim());
    } catch (Exception e) {
        maxWidth = 200; // 200 px 
    }

    FormFile importFile = memberForm.getAvatarUpload();
    overwrite = StringUtil.safeString(memberForm.getAvatarUploadOverwrite());
    String importFileName = getCurrentLoggedInUser(request).getMemberUserName() + "."
            + getFileExtensionForImageReader(importFile.getFileName());
    int size = importFile.getFileSize();

    //--------------------  VALIDATE THE IMAGE -----------------------------------------
    // check width and heigh of image
    logger.debug(importFileName + " ext = " + getFileExtensionForImageReader(importFileName));
    Iterator readers = ImageIO.getImageReadersBySuffix(getFileExtensionForImageReader(importFileName));
    ImageReader reader = (ImageReader) readers.next();

    try {
        ImageInputStream iis = ImageIO.createImageInputStream(importFile.getInputStream());
        reader.setInput(iis, true);
        int width = reader.getWidth(0);
        int height = reader.getHeight(0);
        logger.debug(importFile.getFileName() + ": width=" + width + ", height=" + height);
        if (width > maxWidth || height > maxHeight) {
            errors.add(BaseConstants.WARN_KEY,
                    new ActionMessage("error.dimensions", width, height, maxWidth, maxHeight));
            saveMessages(request, errors);
            return mapping.getInputForward();
        }
    } catch (IOException e) {
        System.err.println(e.getMessage() + ": can't open");
        errors.add(BaseConstants.FATAL_KEY, new ActionMessage("error.notreadable"));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }

    // check file name
    if (importFileName.indexOf(" ") > -1) {
        errors.add(BaseConstants.WARN_KEY, new ActionMessage("error.filename", importFileName));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }

    //boolean validImageName = false;
    /*      StringTokenizer st0 = new StringTokenizer(importFileName, ".");
          if (st0.hasMoreTokens()) {
            if (token.getMemberUserName().equals(st0.nextToken())) {
              //validImageName = true;
            }
            else{
              errors.add(BaseConstants.WARN_KEY, new ActionMessage("error.fileusername", token.getMemberUserName(),importFileName ));
              saveMessages(request, errors);
              return mapping.getInputForward();
            }
          }*/

    File f = new File(avatarDir + importFileName);
    if (f.exists() && (overwrite.equalsIgnoreCase("false") || overwrite.equalsIgnoreCase(""))) {
        continer.setOverWriteAvatar(true);
        errors.add(BaseConstants.WARN_KEY, new ActionMessage("error.filename.exist"));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }

    if (size > maxFileSize) {
        errors.add(BaseConstants.WARN_KEY,
                new ActionMessage("error.filetoobig", String.valueOf(size), String.valueOf(maxFileSize)));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }

    boolean validImageExtension = false;
    StringTokenizer st = new StringTokenizer(fileTypes, ",");

    logger.debug("Current Type = " + importFile.getContentType());
    while (st.hasMoreTokens()) {
        if (importFile.getContentType().equalsIgnoreCase(st.nextToken())) {
            validImageExtension = true;
        }
    }

    // check file extension
    if (!validImageExtension) {
        errors.add(BaseConstants.WARN_KEY, new ActionMessage("error.imageext", String.valueOf(fileTypes)));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }

    // apend the file extension 
    //avatar = avatar + "." + importFile.getContentType();

    //-------------------------------------------------------------

    if (!uploadFromLocalDrive(importFile, importFileName, avatarDir)) {
        errors.add(BaseConstants.FATAL_KEY, new ActionMessage("errors.technical.difficulty"));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }

    memService.updateMemberAvatar(importFileName, token.getMemberUserName(), getLastModifiedBy(request));
    continer.setOverWriteAvatar(false);
    continer.setAvatar(importFileName);
    MemberVO memberVO = memService.getMemberProfileByUserName(token.getMemberUserName());
    BeanUtils.copyProperties(memberForm, memberVO);
    return mapping.findForward(BaseConstants.FWD_SUCCESS);
}

From source file:net.naijatek.myalumni.framework.struts.MyAlumniDispatchAction.java

protected ActionMessages validateUploadFile(HttpServletRequest request, FormFile uploadedFile,
        String fileAllowedTypes, int maxFileSize, boolean validateHeight, int maxHeight, boolean validateWidth,
        int maxWidth) {

    ActionMessages msgs = new ActionMessages();

    String fileName = uploadedFile.getFileName();
    int fileSize = uploadedFile.getFileSize();

    if (fileName == null || fileName.length() == 0) {
        msgs.add(BaseConstants.WARN_KEY, new ActionMessage("error.notreadable"));
    } else {/*from ww w  .j  a  va2 s.co  m*/
        // Check for space in file name
        if (fileName.indexOf(" ") > -1) {
            msgs.add(BaseConstants.WARN_KEY, new ActionMessage("error.filename", fileName));
        }

        // check for file size
        if (fileSize > maxFileSize) {
            msgs.add(BaseConstants.WARN_KEY, new ActionMessage("error.filetoobig", String.valueOf(fileSize),
                    String.valueOf(maxFileSize)));
        }

        boolean validExtension = false;
        StringTokenizer st = new StringTokenizer(fileAllowedTypes, ",");
        while (st.hasMoreTokens()) {
            if (uploadedFile.getContentType().equalsIgnoreCase(st.nextToken())) {
                validExtension = true;
            }
        }

        if (!validExtension) {
            msgs.add(BaseConstants.WARN_KEY,
                    new ActionMessage("error.imageext", SystemConfigConstants.CONTENT_TYPE));
        } else {
            logger.debug(fileName + " ext = " + getFileExtensionForImageReader(fileName));
            Iterator readers = ImageIO.getImageReadersBySuffix(getFileExtensionForImageReader(fileName));
            ImageReader reader = (ImageReader) readers.next();

            try {
                ImageInputStream iis = ImageIO.createImageInputStream(uploadedFile.getInputStream());
                reader.setInput(iis, true);
                int width = reader.getWidth(0);
                int height = reader.getHeight(0);
                logger.debug(uploadedFile.getFileName() + ": width=" + width + ", height=" + height);

                if (validateHeight) {
                    if (height > maxHeight) {
                        msgs.add(BaseConstants.WARN_KEY,
                                new ActionMessage("error.heightdimensions", height, maxHeight));
                    }
                }

                if (validateWidth) {
                    if (width > maxWidth || height > maxHeight) {
                        msgs.add(BaseConstants.WARN_KEY,
                                new ActionMessage("error.widthdimensions", width, maxWidth));
                    }
                }
            } catch (IOException e) {
                msgs.add(BaseConstants.FATAL_KEY, new ActionMessage("error.notreadable"));
            }
        }
    }
    return msgs;
}

From source file:edu.emory.library.tast.images.admin.ImagesBean.java

public String uploadNewImage() {

    try {//from   w w w.j  a  v  a  2s  .com

        if (uploadedImage == null)
            return null;

        // check type
        String extension = (String) allowedTypes.get(uploadedImage.getContentType());
        if (extension == null)
            return null;

        // new filename
        File file = null;
        String fileName = null;
        String imageDir = AppConfig.getConfiguration().getString(AppConfig.IMAGES_DIRECTORY);
        do {
            fileName = new UidGenerator().generate() + "." + extension;
            file = new File(imageDir, fileName);
        } while (file.exists());

        // copy
        FileOutputStream imgFileStream = new FileOutputStream(file);
        int size = IOUtils.copy(uploadedImage.getInputStream(), imgFileStream);
        imgFileStream.flush();
        imgFileStream.close();

        // get image info
        Iterator readerIter = ImageIO.getImageReadersByFormatName(extension);
        ImageReader rdr = (ImageReader) readerIter.next();
        if (rdr == null)
            return null;
        rdr.setInput(ImageIO.createImageInputStream(file), true);

        // get width and height
        int width = rdr.getWidth(0);
        int height = rdr.getHeight(0);

        // replace current image
        imageWidth = width;
        imageHeight = height;
        imageSize = size;
        imageMimeType = uploadedImage.getContentType();
        imageFileName = fileName;

        // all ok
        uploadBoxShown = false;

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return null;
}