Example usage for java.awt.image ColorConvertOp ColorConvertOp

List of usage examples for java.awt.image ColorConvertOp ColorConvertOp

Introduction

In this page you can find the example usage for java.awt.image ColorConvertOp ColorConvertOp.

Prototype

public ColorConvertOp(RenderingHints hints) 

Source Link

Document

Constructs a new ColorConvertOp which will convert from a source color space to a destination color space.

Usage

From source file:com.frochr123.fabqr.FabQRFunctions.java

public static void uploadFabQRProject(String name, String email, String projectName, int licenseIndex,
        String tools, String description, String location, BufferedImage imageReal, BufferedImage imageScheme,
        PlfFile plfFile, String lasercutterName, String lasercutterMaterial) throws Exception {
    // Check for valid situation, otherwise abort
    if (MainView.getInstance() == null || VisicutModel.getInstance() == null
            || VisicutModel.getInstance().getPlfFile() == null || !isFabqrActive()
            || getFabqrPrivateURL() == null || getFabqrPrivateURL().isEmpty()
            || MaterialManager.getInstance() == null || MappingManager.getInstance() == null
            || VisicutModel.getInstance().getSelectedLaserDevice() == null) {
        throw new Exception("FabQR upload exception: Critical error");
    }/*w w  w . j ava 2 s  .c  om*/

    // Check valid data
    if (name == null || email == null || projectName == null || projectName.length() < 3 || licenseIndex < 0
            || tools == null || tools.isEmpty() || description == null || description.isEmpty()
            || location == null || location.isEmpty() || imageScheme == null || plfFile == null
            || lasercutterName == null || lasercutterName.isEmpty() || lasercutterMaterial == null
            || lasercutterMaterial.isEmpty()) {
        throw new Exception("FabQR upload exception: Invalid input data");
    }

    // Convert images to byte data for PNG, imageReal is allowed to be empty
    byte[] imageSchemeBytes = null;
    ByteArrayOutputStream imageSchemeOutputStream = new ByteArrayOutputStream();
    PreviewImageExport.writePngToOutputStream(imageSchemeOutputStream, imageScheme);
    imageSchemeBytes = imageSchemeOutputStream.toByteArray();

    if (imageSchemeBytes == null) {
        throw new Exception("FabQR upload exception: Error converting scheme image");
    }

    byte[] imageRealBytes = null;

    if (imageReal != null) {
        // Need to convert image, ImageIO.write messes up the color space of the original input image
        BufferedImage convertedImage = new BufferedImage(imageReal.getWidth(), imageReal.getHeight(),
                BufferedImage.TYPE_3BYTE_BGR);
        ColorConvertOp op = new ColorConvertOp(null);
        op.filter(imageReal, convertedImage);

        ByteArrayOutputStream imageRealOutputStream = new ByteArrayOutputStream();
        ImageIO.write(convertedImage, "jpg", imageRealOutputStream);
        imageRealBytes = imageRealOutputStream.toByteArray();
    }

    // Extract all URLs from used QR codes
    List<String> referencesList = new LinkedList<String>();
    List<PlfPart> plfParts = plfFile.getPartsCopy();

    for (PlfPart plfPart : plfParts) {
        if (plfPart.getQRCodeInfo() != null && plfPart.getQRCodeInfo().getQRCodeSourceURL() != null
                && !plfPart.getQRCodeInfo().getQRCodeSourceURL().trim().isEmpty()) {
            // Process url, if it is URL of a FabQR system, remove download flag and point to project page instead
            // Use regex to check for FabQR system URL structure
            String qrCodeUrl = plfPart.getQRCodeInfo().getQRCodeSourceURL().trim();

            // Check for temporary URL structure of FabQR system
            Pattern fabQRUrlTemporaryPattern = Pattern
                    .compile("^https{0,1}://.*?" + "/" + FABQR_TEMPORARY_MARKER + "/" + "([a-z]|[0-9]){7,7}$");

            // Do not include link if it is just temporary
            if (fabQRUrlTemporaryPattern.matcher(qrCodeUrl).find()) {
                continue;
            }

            // Check for download URL structure of FabQR system
            // Change URL to point to project page instead
            Pattern fabQRUrlDownloadPattern = Pattern
                    .compile("^https{0,1}://.*?" + "/" + FABQR_DOWNLOAD_MARKER + "/" + "([a-z]|[0-9]){7,7}$");

            if (fabQRUrlDownloadPattern.matcher(qrCodeUrl).find()) {
                qrCodeUrl = qrCodeUrl.replace("/" + FABQR_DOWNLOAD_MARKER + "/", "/");
            }

            // Add URL if it is not yet in list
            if (!referencesList.contains(qrCodeUrl)) {
                referencesList.add(qrCodeUrl);
            }
        }
    }

    String references = "";

    for (String ref : referencesList) {
        // Add comma for non first entries
        if (!references.isEmpty()) {
            references = references + ",";
        }

        references = references + ref;
    }

    // Get bytes for PLF file
    byte[] plfFileBytes = null;
    ByteArrayOutputStream plfFileOutputStream = new ByteArrayOutputStream();
    VisicutModel.getInstance().savePlfToStream(MaterialManager.getInstance(), MappingManager.getInstance(),
            plfFileOutputStream);
    plfFileBytes = plfFileOutputStream.toByteArray();

    if (plfFileBytes == null) {
        throw new Exception("FabQR upload exception: Error saving PLF file");
    }

    // Begin uploading data
    String uploadUrl = getFabqrPrivateURL() + FABQR_API_UPLOAD_PROJECT;

    // Create HTTP client and cusomized config for timeouts
    CloseableHttpClient httpClient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(FABQR_UPLOAD_TIMEOUT)
            .setConnectTimeout(FABQR_UPLOAD_TIMEOUT).setConnectionRequestTimeout(FABQR_UPLOAD_TIMEOUT).build();

    // Create HTTP Post request and entity builder
    HttpPost httpPost = new HttpPost(uploadUrl);
    httpPost.setConfig(requestConfig);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    // Insert file uploads
    multipartEntityBuilder.addBinaryBody("imageScheme", imageSchemeBytes, ContentType.APPLICATION_OCTET_STREAM,
            "imageScheme.png");
    multipartEntityBuilder.addBinaryBody("inputFile", plfFileBytes, ContentType.APPLICATION_OCTET_STREAM,
            "inputFile.plf");

    // Image real is allowed to be null, if it is not, send it
    if (imageRealBytes != null) {
        multipartEntityBuilder.addBinaryBody("imageReal", imageRealBytes, ContentType.APPLICATION_OCTET_STREAM,
                "imageReal.png");
    }

    // Prepare content type for text data, especially needed for correct UTF8 encoding
    ContentType contentType = ContentType.create("text/plain", Consts.UTF_8);

    // Insert text data
    multipartEntityBuilder.addTextBody("name", name, contentType);
    multipartEntityBuilder.addTextBody("email", email, contentType);
    multipartEntityBuilder.addTextBody("projectName", projectName, contentType);
    multipartEntityBuilder.addTextBody("licenseIndex", new Integer(licenseIndex).toString(), contentType);
    multipartEntityBuilder.addTextBody("tools", tools, contentType);
    multipartEntityBuilder.addTextBody("description", description, contentType);
    multipartEntityBuilder.addTextBody("location", location, contentType);
    multipartEntityBuilder.addTextBody("lasercutterName", lasercutterName, contentType);
    multipartEntityBuilder.addTextBody("lasercutterMaterial", lasercutterMaterial, contentType);
    multipartEntityBuilder.addTextBody("references", references, contentType);

    // Assign entity to this post request
    HttpEntity httpEntity = multipartEntityBuilder.build();
    httpPost.setEntity(httpEntity);

    // Set authentication information
    String encodedCredentials = Helper.getEncodedCredentials(FabQRFunctions.getFabqrPrivateUser(),
            FabQRFunctions.getFabqrPrivatePassword());
    if (!encodedCredentials.isEmpty()) {
        httpPost.addHeader("Authorization", "Basic " + encodedCredentials);
    }

    // Send request
    CloseableHttpResponse res = httpClient.execute(httpPost);

    // React to possible server side errors
    if (res.getStatusLine() == null || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new Exception("FabQR upload exception: Server sent wrong HTTP status code: "
                + new Integer(res.getStatusLine().getStatusCode()).toString());
    }

    // Close everything correctly
    res.close();
    httpClient.close();
}

From source file:org.geomajas.plugin.rasterizing.layer.RasterDirectLayer.java

/**
 * Converts an image to a RGBA direct color model using a workaround via buffered image directly calling the
 * ColorConvert operation fails for unknown reasons ?!
 * /*from  w  w  w  .  j a  v a2s .  c o m*/
 * @param img image to convert
 * @return converted image
 */
public PlanarImage toDirectColorModel(RenderedImage img) {
    BufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
    BufferedImage source = new BufferedImage(img.getColorModel(), (WritableRaster) img.getData(),
            img.getColorModel().isAlphaPremultiplied(), null);
    ColorConvertOp op = new ColorConvertOp(null);
    op.filter(source, dest);
    return PlanarImage.wrapRenderedImage(dest);
}

From source file:org.sejda.sambox.pdmodel.graphics.image.JPEGFactory.java

private static BufferedImage getColorImage(BufferedImage image) {
    if (!image.getColorModel().hasAlpha()) {
        return image;
    }/*www  .  j  a  v a  2 s  . c  o  m*/

    if (image.getColorModel().getColorSpace().getType() != ColorSpace.TYPE_RGB) {
        throw new UnsupportedOperationException("only RGB color spaces are implemented");
    }

    // create an RGB image without alpha
    // BEWARE: the previous solution in the history
    // g.setComposite(AlphaComposite.Src) and g.drawImage()
    // didn't work properly for TYPE_4BYTE_ABGR.
    // alpha values of 0 result in a black dest pixel!!!
    BufferedImage rgbImage = new BufferedImage(image.getWidth(), image.getHeight(),
            BufferedImage.TYPE_3BYTE_BGR);
    return new ColorConvertOp(null).filter(image, rgbImage);
}

From source file:org.tinymediamanager.core.ImageCache.java

/**
 * Scale image to fit in the given width.
 * //from   w  ww. j  av a2  s.  c o  m
 * @param imageUrl
 *          the image url
 * @param width
 *          the width
 * @return the input stream
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 * @throws InterruptedException
 */
public static InputStream scaleImage(String imageUrl, int width) throws IOException, InterruptedException {
    Url url = new Url(imageUrl);

    BufferedImage originalImage = null;
    try {
        originalImage = createImage(url.getBytes());
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }

    Point size = new Point();
    size.x = width;
    size.y = size.x * originalImage.getHeight() / originalImage.getWidth();

    // BufferedImage scaledImage = Scaling.scale(originalImage, size.x, size.y);
    BufferedImage scaledImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, size.x,
            size.y, Scalr.OP_ANTIALIAS);
    originalImage = null;

    ImageWriter imgWrtr = null;
    ImageWriteParam imgWrtrPrm = null;

    // here we have two different ways to create our thumb
    // a) a scaled down jpg/png (without transparency) which we have to modify since OpenJDK cannot call native jpg encoders
    // b) a scaled down png (with transparency) which we can store without any more modifying as png
    if (hasTransparentPixels(scaledImage)) {
        // transparent image -> png
        imgWrtr = ImageIO.getImageWritersByFormatName("png").next();
        imgWrtrPrm = imgWrtr.getDefaultWriteParam();

    } else {
        // non transparent image -> jpg
        // convert to rgb
        BufferedImage rgb = new BufferedImage(scaledImage.getWidth(), scaledImage.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        ColorConvertOp xformOp = new ColorConvertOp(null);
        xformOp.filter(scaledImage, rgb);
        imgWrtr = ImageIO.getImageWritersByFormatName("jpg").next();
        imgWrtrPrm = imgWrtr.getDefaultWriteParam();
        imgWrtrPrm.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
        imgWrtrPrm.setCompressionQuality(0.80f);

        scaledImage = rgb;
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageOutputStream output = ImageIO.createImageOutputStream(baos);
    imgWrtr.setOutput(output);
    IIOImage outputImage = new IIOImage(scaledImage, null, null);
    imgWrtr.write(null, outputImage, imgWrtrPrm);
    imgWrtr.dispose();
    scaledImage = null;

    byte[] bytes = baos.toByteArray();

    output.flush();
    output.close();
    baos.close();

    return new ByteArrayInputStream(bytes);
}

From source file:org.tinymediamanager.core.ImageCache.java

/**
 * Scale image to fit in the given width.
 * /*from  w w w. j  a v a  2s.c  o m*/
 * @param file
 *          the original image file
 * @param width
 *          the width
 * @return the input stream
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 * @throws InterruptedException
 */
public static InputStream scaleImage(Path file, int width) throws IOException, InterruptedException {
    BufferedImage originalImage = null;
    try {
        originalImage = createImage(file);
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }

    Point size = new Point();
    size.x = width;
    size.y = size.x * originalImage.getHeight() / originalImage.getWidth();

    // BufferedImage scaledImage = Scaling.scale(originalImage, size.x, size.y);
    BufferedImage scaledImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.AUTOMATIC, size.x,
            size.y, Scalr.OP_ANTIALIAS);
    originalImage = null;

    ImageWriter imgWrtr = null;
    ImageWriteParam imgWrtrPrm = null;

    // here we have two different ways to create our thumb
    // a) a scaled down jpg/png (without transparency) which we have to modify since OpenJDK cannot call native jpg encoders
    // b) a scaled down png (with transparency) which we can store without any more modifying as png
    if (hasTransparentPixels(scaledImage)) {
        // transparent image -> png
        imgWrtr = ImageIO.getImageWritersByFormatName("png").next();
        imgWrtrPrm = imgWrtr.getDefaultWriteParam();

    } else {
        // non transparent image -> jpg
        // convert to rgb
        BufferedImage rgb = new BufferedImage(scaledImage.getWidth(), scaledImage.getHeight(),
                BufferedImage.TYPE_INT_RGB);
        ColorConvertOp xformOp = new ColorConvertOp(null);
        xformOp.filter(scaledImage, rgb);
        imgWrtr = ImageIO.getImageWritersByFormatName("jpg").next();
        imgWrtrPrm = imgWrtr.getDefaultWriteParam();
        imgWrtrPrm.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
        imgWrtrPrm.setCompressionQuality(0.80f);

        scaledImage = rgb;
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageOutputStream output = ImageIO.createImageOutputStream(baos);
    imgWrtr.setOutput(output);
    IIOImage outputImage = new IIOImage(scaledImage, null, null);
    imgWrtr.write(null, outputImage, imgWrtrPrm);
    imgWrtr.dispose();
    scaledImage = null;

    byte[] bytes = baos.toByteArray();

    output.flush();
    output.close();
    baos.close();

    return new ByteArrayInputStream(bytes);
}

From source file:org.tinymediamanager.core.ImageCache.java

/**
 * Cache image./*from  w  w w .  j  a v a2  s . c  o m*/
 * 
 * @param mf
 *          the media file
 * @return the file the cached file
 * @throws Exception
 */
public static Path cacheImage(Path originalFile) throws Exception {
    MediaFile mf = new MediaFile(originalFile);
    Path cachedFile = ImageCache.getCacheDir()
            .resolve(getMD5(originalFile.toString()) + "." + Utils.getExtension(originalFile));
    if (!Files.exists(cachedFile)) {
        // check if the original file exists && size > 0
        if (!Files.exists(originalFile)) {
            throw new FileNotFoundException("unable to cache file: " + originalFile + "; file does not exist");
        }
        if (Files.size(originalFile) == 0) {
            throw new EmptyFileException(originalFile);
        }

        // recreate cache dir if needed
        // rescale & cache
        BufferedImage originalImage = null;
        try {
            originalImage = createImage(originalFile);
        } catch (Exception e) {
            throw new Exception("cannot create image - file seems not to be valid? " + originalFile);
        }

        // calculate width based on MF type
        int desiredWidth = originalImage.getWidth(); // initialize with fallback
        switch (mf.getType()) {
        case FANART:
            if (originalImage.getWidth() > 1000) {
                desiredWidth = 1000;
            }
            break;

        case POSTER:
            if (originalImage.getHeight() > 500) {
                desiredWidth = 350;
            }
            break;

        case EXTRAFANART:
        case THUMB:
        case BANNER:
        case GRAPHIC:
            desiredWidth = 300;
            break;

        default:
            break;
        }

        // special handling for movieset-fanart or movieset-poster
        if (mf.getFilename().startsWith("movieset-fanart") || mf.getFilename().startsWith("movieset-poster")) {
            if (originalImage.getWidth() > 1000) {
                desiredWidth = 1000;
            }
        }

        Point size = calculateSize(desiredWidth, (int) (originalImage.getHeight() / 1.5),
                originalImage.getWidth(), originalImage.getHeight(), true);
        BufferedImage scaledImage = null;

        if (Globals.settings.getImageCacheType() == CacheType.FAST) {
            // scale fast
            scaledImage = Scalr.resize(originalImage, Scalr.Method.BALANCED, Scalr.Mode.FIT_EXACT, size.x,
                    size.y);
        } else {
            // scale with good quality
            scaledImage = Scalr.resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT, size.x,
                    size.y);
        }
        originalImage = null;

        ImageWriter imgWrtr = null;
        ImageWriteParam imgWrtrPrm = null;

        // here we have two different ways to create our thumb
        // a) a scaled down jpg/png (without transparency) which we have to modify since OpenJDK cannot call native jpg encoders
        // b) a scaled down png (with transparency) which we can store without any more modifying as png
        if (hasTransparentPixels(scaledImage)) {
            // transparent image -> png
            imgWrtr = ImageIO.getImageWritersByFormatName("png").next();
            imgWrtrPrm = imgWrtr.getDefaultWriteParam();

        } else {
            // non transparent image -> jpg
            // convert to rgb
            BufferedImage rgb = new BufferedImage(scaledImage.getWidth(), scaledImage.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
            ColorConvertOp xformOp = new ColorConvertOp(null);
            xformOp.filter(scaledImage, rgb);
            imgWrtr = ImageIO.getImageWritersByFormatName("jpg").next();
            imgWrtrPrm = imgWrtr.getDefaultWriteParam();
            imgWrtrPrm.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
            imgWrtrPrm.setCompressionQuality(0.80f);

            scaledImage = rgb;
        }

        FileImageOutputStream output = new FileImageOutputStream(cachedFile.toFile());
        imgWrtr.setOutput(output);
        IIOImage image = new IIOImage(scaledImage, null, null);
        imgWrtr.write(null, image, imgWrtrPrm);
        imgWrtr.dispose();
        output.flush();
        output.close();
        scaledImage = null;
    }

    if (!Files.exists(cachedFile)) {
        throw new Exception("unable to cache file: " + originalFile);
    }

    return cachedFile;
}