Example usage for java.awt.image ColorConvertOp filter

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

Introduction

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

Prototype

public final WritableRaster filter(Raster src, WritableRaster dest) 

Source Link

Document

ColorConverts the image data in the source Raster.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    BufferedImage master = ImageIO.read(new URL("http://www.java2s.com/style/download.png"));
    BufferedImage gray = new BufferedImage(master.getWidth(), master.getHeight(), BufferedImage.TYPE_INT_ARGB);

    ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
    op.filter(master, gray);

    // new JLabel(new ImageIcon(master));
    // new JLabel(new ImageIcon(gray));
    ImageIO.write(master, "png", new File("c:/Java_Dev/master.png"));
    ImageIO.write(gray, "png", new File("c:/Java_Dev/gray.png"));
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int size = 120;
    int pad = 10;
    BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.createGraphics();
    g.setColor(Color.WHITE);//from  w w  w.  j a v  a 2s .  c  o  m
    g.fillRect(0, 0, size, size);
    g.setColor(Color.YELLOW);
    g.fillOval(pad, pad, size - (2 * pad), size - (2 * pad));
    g.dispose();

    BufferedImage image2 = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_BYTE_GRAY);

    ColorConvertOp op = new ColorConvertOp(bi.getColorModel().getColorSpace(),
            image2.getColorModel().getColorSpace(), null);
    op.filter(bi, image2);
    ImageIO.write(image2, "png", new File("c:/Java_Dev/image2.png"));
}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
    ColorConvertOp op = new ColorConvertOp(cs, null);

    BufferedImage bufferedImage = new BufferedImage(200, 200, BufferedImage.TYPE_BYTE_INDEXED);
    bufferedImage = op.filter(bufferedImage, null);
}

From source file:ImageUtil.java

public static BufferedImage desaturate(BufferedImage source) {
    ColorConvertOp colorConvert = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
    colorConvert.filter(source, source);

    return source;
}

From source file:ConvertUtil.java

/**
 * Converts the source image to 8-bit colour using the default 256-colour
 * palette. No transparency.//  w w w.j a  v a  2  s  .c o m
 * 
 * @param src
 *            the source image to convert
 * @return a copy of the source image with an 8-bit colour depth
 */
public static BufferedImage convert8(BufferedImage src) {
    BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
    ColorConvertOp cco = new ColorConvertOp(src.getColorModel().getColorSpace(),
            dest.getColorModel().getColorSpace(), null);
    cco.filter(src, dest);
    return dest;
}

From source file:ConvertUtil.java

/**
 * Converts the source image to 24-bit colour (RGB). No transparency.
 * /*from   ww  w .j a v a2s.  co  m*/
 * @param src
 *            the source image to convert
 * @return a copy of the source image with a 24-bit colour depth
 */
public static BufferedImage convert24(BufferedImage src) {
    BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_RGB);
    ColorConvertOp cco = new ColorConvertOp(src.getColorModel().getColorSpace(),
            dest.getColorModel().getColorSpace(), null);
    cco.filter(src, dest);
    return dest;
}

From source file:ConvertUtil.java

/**
 * Converts the source image to 32-bit colour with transparency (ARGB).
 * //  w  w  w .  j av a2s  . c  o  m
 * @param src
 *            the source image to convert
 * @return a copy of the source image with a 32-bit colour depth.
 */
public static BufferedImage convert32(BufferedImage src) {
    BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB);
    ColorConvertOp cco = new ColorConvertOp(src.getColorModel().getColorSpace(),
            dest.getColorModel().getColorSpace(), null);
    cco.filter(src, dest);
    return dest;
}

From source file:ConvertUtil.java

/**
 * Converts the source image to 4-bit colour using the given colour map. No
 * transparency./*from w w w  .j  a v a 2  s  . c  o m*/
 * 
 * @param src
 *            the source image to convert
 * @param cmap
 *            the colour map, which should contain no more than 16 entries
 *            The entries are in the form RRGGBB (hex).
 * @return a copy of the source image with a 4-bit colour depth, with the
 *         custom colour pallette
 */
public static BufferedImage convert4(BufferedImage src, int[] cmap) {
    IndexColorModel icm = new IndexColorModel(4, cmap.length, cmap, 0, false, Transparency.OPAQUE,
            DataBuffer.TYPE_BYTE);
    BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_BINARY,
            icm);
    ColorConvertOp cco = new ColorConvertOp(src.getColorModel().getColorSpace(),
            dest.getColorModel().getColorSpace(), null);
    cco.filter(src, dest);

    return dest;
}

From source file:ConvertUtil.java

/**
 * Converts the source to 1-bit colour depth (monochrome). No transparency.
 * /* w w  w .  j a v a2s .  c om*/
 * @param src
 *            the source image to convert
 * @return a copy of the source image with a 1-bit colour depth.
 */
public static BufferedImage convert1(BufferedImage src) {
    IndexColorModel icm = new IndexColorModel(1, 2, new byte[] { (byte) 0, (byte) 0xFF },
            new byte[] { (byte) 0, (byte) 0xFF }, new byte[] { (byte) 0, (byte) 0xFF });

    BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_BINARY,
            icm);

    ColorConvertOp cco = new ColorConvertOp(src.getColorModel().getColorSpace(),
            dest.getColorModel().getColorSpace(), null);

    cco.filter(src, dest);

    return dest;
}

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  a  v a  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();
}