Java Code Examples for java.awt.image.BufferedImage.getTransparency()

The following are Jave code examples for showing how to use getTransparency() of the java.awt.image.BufferedImage class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: JMELink-SP   File: PhongSubstance.java   View Source Code Vote up 7 votes
@Override
public String getOutputFormat(String tx_name,String tx_path,String substance_fs_path) {
	tx_name=tx_name.substring(tx_name.lastIndexOf("_")+1);
	boolean has_alpha=false;
	try{
		BufferedImage bimg=ImageIO.read(new File(PathUtils.toNative(substance_fs_path+tx_path)));
		has_alpha=bimg.getTransparency()==BufferedImage.TRANSLUCENT;
	}catch(Exception e){
		LOGGER.log(Level.WARNING,"Can't read image",e);
	}
	if(has_alpha)LOGGER.log(Level.FINE,tx_name+" has alpha channel.");
	switch(tx_name){
		case "DiffuseMap":
			return has_alpha?"S3TC_DXT5":"S3TC_DXT1";
		case "SpecularMap":
			return "S3TC_DXT1";
		case "GlowMap":
			return "S3TC_DXT1";
	
		case "NormalMap":
			return "rgb8";
		case "ParallaxMap":
			return "rgb8";
	}
	return null;
}
 
Example 2
Project: VASSAL-src   File: ImageUtils.java   View Source Code Vote up 6 votes
public static BufferedImage toCompatibleImage(BufferedImage src) {
  if ((src.getColorModel().equals(compatOpaqueImage.getColorModel()) &&
       src.getTransparency() == compatOpaqueImage.getTransparency())
      ||
      (src.getColorModel().equals(compatTransImage.getColorModel()) &&
       src.getTransparency() == compatTransImage.getTransparency()))
  {
    return src;
  }

  final BufferedImage dst = createCompatibleImage(
    src.getWidth(), src.getHeight(), isTransparent(src)
  );

  final Graphics2D g = dst.createGraphics();
  g.drawImage(src, 0, 0, null);
  g.dispose();

  return dst;
}
 
Example 3
Project: lemon-framework   File: ImageUtil.java   View Source Code Vote up 6 votes
/**
 * 按比例缩放
 * @param img
 * @return
 */
public static BufferedImage getScaleZoom(BufferedImage img, int targetSize) {
	int srcWidth = img.getWidth();
	int srcHeight = img.getHeight();
	int targetWidth = targetSize;
	int targetHeight = targetSize;
	if (targetSize>srcWidth || targetSize>srcHeight){
		targetWidth = srcWidth;
		targetHeight = srcHeight;
	}
	double rate1 = ((double)srcWidth)/targetWidth;
	double rate2 = ((double)srcHeight)/targetHeight;
       // 根据缩放比率大的进行缩放控制 
       double rate = rate1 > rate2 ? rate1 : rate2;
       int newWidth = (int)(((double)srcWidth)/rate);
       int newHeight = (int)(((double)srcHeight)/rate);
	int imageType = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
	BufferedImage tag = new BufferedImage(newWidth, newHeight, imageType);
	//Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的优先级比速度高 生成的图片质量比较好 但速度慢
	Image scaledImage = img.getScaledInstance(newWidth, newHeight, Image.SCALE_REPLICATE);
	tag.getGraphics().drawImage(scaledImage, 0, 0, null);
	
	return tag;
}
 
Example 4
Project: JMELink-SP   File: PBRSubstance.java   View Source Code Vote up 5 votes
@Override
public String getOutputFormat(String tx_name, String tx_path, String substance_fs_path) {
	if(tx_path.isEmpty()) return tx_path;
	tx_name=tx_name.substring(tx_name.lastIndexOf("_")+1);
	boolean has_alpha=false;
	try{
		File f=new File(PathUtils.toNative(substance_fs_path+"/"+tx_path));
		System.out.println(f);
		BufferedImage bimg=ImageIO.read(f);
		has_alpha=bimg.getTransparency()==BufferedImage.TRANSLUCENT;
	}catch(Exception e){
		LOGGER.log(Level.WARNING,"Can't read image",e);
	}
	if(has_alpha) LOGGER.log(Level.FINE,tx_name+" has alpha channel.");
	switch(tx_name){
		case "BaseColorMap":
			return has_alpha?"S3TC_DXT5":"S3TC_DXT1";
		case "MetallicMap":
			return "S3TC_DXT1";
		case "RoughnessMap":
			return "S3TC_DXT1";
		case "EmissiveMap":
			return "S3TC_DXT1";
		case "NormalMap":
			return "rgb8";
		case "ParallaxMap":
			return "rgb8";
	}
	return null;
}
 
Example 5
Project: opentest   File: ImageUtil.java   View Source Code Vote up 5 votes
public static BufferedImage cloneImageRegion(BufferedImage srcImg, int x, int y, int width, int height) {
    int imgType = (srcImg.getTransparency() == Transparency.OPAQUE)
            ? BufferedImage.TYPE_INT_RGB
            : BufferedImage.TYPE_INT_ARGB;
    BufferedImage newImage = new BufferedImage(width, height, imgType);
    Graphics2D g2 = newImage.createGraphics();
    g2.drawImage(srcImg.getSubimage(x, y, width, height), 0, 0, null);
    g2.dispose();

    return newImage;
}
 
Example 6
Project: lemon-framework   File: ImageUtil.java   View Source Code Vote up 5 votes
/**
 * 按比例裁剪
 * @param img
 * @param targetWidth
 * @param targetHeight
 * @return
 */
public static BufferedImage getScaleCutscale(BufferedImage img, int targetWidth, int targetHeight) {
	int srcWidth = img.getWidth();
	int srcHeight = img.getHeight();
	//当超过图片最大宽高时候等比缩小所需要的图片规格
	while(targetWidth>srcWidth || targetHeight>srcHeight){
		double rt = (targetWidth>srcWidth)? ((double)targetWidth)/(srcWidth): ((double)targetHeight)/(srcHeight);
		targetWidth = (int)(((double)targetWidth)/rt);
		targetHeight = (int)(((double)targetHeight)/rt);
	}

	double rate1 = ((double)srcWidth)/(targetWidth);
	double rate2 = ((double)srcHeight)/(targetHeight);
       // 根据缩放比率大的进行缩放控制 
       double rate = rate1 < rate2 ? rate1 : rate2; 
       int newWidth = (int)(((double)srcWidth)/rate);
       int newHeight = (int)(((double)srcHeight)/rate);

       int x1 = newWidth/2 - targetWidth/2;
       int x2 = newWidth/2 + targetWidth/2;
       int y1 = newHeight/2 - targetHeight/2;
       int y2 = newHeight/2 + targetHeight/2;
	int imageType = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
	BufferedImage tag = new BufferedImage(targetWidth, targetHeight, imageType);
    Image scaledImage = img.getScaledInstance(newWidth, newHeight, Image.SCALE_REPLICATE);
	tag.getGraphics().drawImage(scaledImage, 0, 0, targetWidth, targetHeight, x1, y1, x2, y2, null);
	
	return tag;
}
 
Example 7
Project: VASSAL-src   File: ImageUtils.java   View Source Code Vote up 4 votes
public static boolean isTransparent(BufferedImage img) {
  return img.getTransparency() != BufferedImage.OPAQUE;
}
 
Example 8
Project: VASSAL-src   File: GeneralFilter.java   View Source Code Vote up 4 votes
/**
 * Filters a portion of the source image.
 *
 * @param dstR the destination tile to calculate
 * @param dst_fr the bounds of the whole destination image
 * @param srcI the source image
 * @param filter the filter to apply
 * @throws ClassCastException if <code>srcI</code> does not store its data
 * in a {@link DataBufferInt}
 */
public static void zoom(
  WritableRaster dstR,
  Rectangle dst_fr,
  BufferedImage srcI,
  final Filter filter)
{
  final int dst_data[] = ((DataBufferInt) dstR.getDataBuffer()).getData();

  final int src_type;
  if (srcI.getTransparency() == BufferedImage.OPAQUE) {
    src_type = OPAQUE;
  }
  else if (srcI.isAlphaPremultiplied()) {
    src_type = TRANS_PREMULT;
  }
  else {
    src_type = TRANS_UNPREMULT;
  }

  final int dx0 = dstR.getMinX();
  final int dy0 = dstR.getMinY();
  final int dx1 = dx0 + dstR.getWidth() - 1;
  final int dy1 = dy0 + dstR.getHeight() - 1;
  final int dw = dstR.getWidth();
  final int dh = dstR.getHeight();

  final int dstWidth = dst_fr.width;
  final int dstHeight = dst_fr.height;

  final int srcWidth = srcI.getWidth();
  final int srcHeight = srcI.getHeight();

  // We want dstX0 * xscale = srcX0, except when that would make
  // xscale = 0; similarly for yscale.
  final float xscale =
    srcWidth == 1 ? dstWidth : (float)(dstWidth-1) / (srcWidth-1);
  final float yscale =
    srcHeight == 1 ? dstHeight : (float)(dstHeight-1) / (srcHeight-1);

  final float fwidth = filter.getSamplingRadius();

  final int sx0 = Math.max(0, (int) Math.floor((dx0-fwidth)/xscale));
  final int sy0 = Math.max(0, (int) Math.floor((dy0-fwidth)/yscale));
  final int sx1 = Math.min(srcWidth-1, (int) Math.ceil((dx1+fwidth)/xscale));
  final int sy1 = Math.min(srcHeight-1, (int) Math.ceil((dy1+fwidth)/yscale));
  final int sw = sx1 - sx0 + 1;
  final int sh = sy1 - sy0 + 1;

  final int src_data[] =
    ((DataBufferInt) srcI.getRaster().getDataBuffer()).getData();

  resample(
    src_data, false,
    sx0, sy0, sx1, sy1, sw, sh, src_type, srcWidth, srcHeight,
    dst_data, dx0, dy0, dx1, dy1, dw, dh, dstWidth, dstHeight,
    xscale, yscale, filter
  );
}
 
Example 9
Project: lams   File: Scalr.java   View Source Code Vote up 4 votes
/**
    * Used to copy a {@link BufferedImage} from a non-optimal type into a new
    * {@link BufferedImage} instance of an optimal type (RGB or ARGB). If
    * <code>src</code> is already of an optimal type, then it is returned
    * unmodified.
    * <p/>
    * This method is meant to be used by any calling code (imgscalr's or
    * otherwise) to convert any inbound image from a poorly supported image
    * type into the 2 most well-supported image types in Java2D (
    * {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_ARGB}
    * ) in order to ensure all subsequent graphics operations are performed as
    * efficiently and correctly as possible.
    * <p/>
    * When using Java2D to work with image types that are not well supported,
    * the results can be anything from exceptions bubbling up from the depths
    * of Java2D to images being completely corrupted and just returned as solid
    * black.
    * 
    * @param src
    *            The image to copy (if necessary) into an optimally typed
    *            {@link BufferedImage}.
    * 
    * @return a representation of the <code>src</code> image in an optimally
    *         typed {@link BufferedImage}, otherwise <code>src</code> if it was
    *         already of an optimal type.
    * 
    * @throws IllegalArgumentException
    *             if <code>src</code> is <code>null</code>.
    */
   protected static BufferedImage copyToOptimalImage(BufferedImage src) throws IllegalArgumentException {
if (src == null)
    throw new IllegalArgumentException("src cannot be null");

// Calculate the type depending on the presence of alpha.
int type = (src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB
	: BufferedImage.TYPE_INT_ARGB);
BufferedImage result = new BufferedImage(src.getWidth(), src.getHeight(), type);

// Render the src image into our new optimal source.
Graphics g = result.getGraphics();
g.drawImage(src, 0, 0, null);
g.dispose();

return result;
   }
 
Example 10
Project: ConvNetCL4J   File: Scalr.java   View Source Code Vote up 4 votes
/**
 * Used to copy a {@link BufferedImage} from a non-optimal type into a new
 * {@link BufferedImage} instance of an optimal type (RGB or ARGB). If
 * <code>src</code> is already of an optimal type, then it is returned
 * unmodified.
 * <p/>
 * This method is meant to be used by any calling code (imgscalr's or
 * otherwise) to convert any inbound image from a poorly supported image
 * type into the 2 most well-supported image types in Java2D (
 * {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_ARGB}
 * ) in order to ensure all subsequent graphics operations are performed as
 * efficiently and correctly as possible.
 * <p/>
 * When using Java2D to work with image types that are not well supported,
 * the results can be anything from exceptions bubbling up from the depths
 * of Java2D to images being completely corrupted and just returned as solid
 * black.
 * 
 * @param src
 *            The image to copy (if necessary) into an optimally typed
 *            {@link BufferedImage}.
 * 
 * @return a representation of the <code>src</code> image in an optimally
 *         typed {@link BufferedImage}, otherwise <code>src</code> if it was
 *         already of an optimal type.
 * 
 * @throws IllegalArgumentException
 *             if <code>src</code> is <code>null</code>.
 */
protected static BufferedImage copyToOptimalImage(BufferedImage src)
		throws IllegalArgumentException {
	if (src == null)
		throw new IllegalArgumentException("src cannot be null");

	// Calculate the type depending on the presence of alpha.
	int type = (src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB
			: BufferedImage.TYPE_INT_ARGB);
	BufferedImage result = new BufferedImage(src.getWidth(),
			src.getHeight(), type);

	// Render the src image into our new optimal source.
	Graphics g = result.getGraphics();
	g.drawImage(src, 0, 0, null);
	g.dispose();

	return result;
}
 
Example 11
Project: Yass   File: YassUtils.java   View Source Code Vote up 4 votes
/**
 * Gets the scaledInstance attribute of the YassUtils object
 *
 * @param img          Description of the Parameter
 * @param targetWidth  Description of the Parameter
 * @param targetHeight Description of the Parameter
 * @return The scaledInstance value
 */
public static BufferedImage getScaledInstance(BufferedImage img, int targetWidth, int targetHeight) {
    boolean higherQuality = true;
    Object hint = RenderingHints.VALUE_INTERPOLATION_BICUBIC;

    int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
    BufferedImage ret = img;
    int w;
    int h;
    if (higherQuality) {
        // Use multi-step technique: start with original size, then
        // scale down in multiple passes with drawImage()
        // until the target size is reached
        w = img.getWidth();
        h = img.getHeight();
    } else {
        // Use one-step technique: scale directly from original
        // size to target size with a single drawImage() call
        w = targetWidth;
        h = targetHeight;
    }

    do {
        if (higherQuality && w > targetWidth) {
            w /= 2;
            if (w < targetWidth) {
                w = targetWidth;
            }
        }

        if (higherQuality && h > targetHeight) {
            h /= 2;
            if (h < targetHeight) {
                h = targetHeight;
            }
        }

        BufferedImage tmp = new BufferedImage(w, h, type);
        Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
        g2.drawImage(ret, 0, 0, w, h, null);
        g2.dispose();

        ret = tmp;
    } while (w != targetWidth || h != targetHeight);

    return ret;
}
 
Example 12
Project: lams   File: Scalr.java   View Source Code Vote up 3 votes
/**
    * Used to create a {@link BufferedImage} with the given dimensions and the
    * most optimal RGB TYPE ( {@link BufferedImage#TYPE_INT_RGB} or
    * {@link BufferedImage#TYPE_INT_ARGB} ) capable of being rendered into from
    * the given <code>src</code>.
    * <p/>
    * This does not perform a copy of the image data from <code>src</code> into
    * the result image; see {@link #copyToOptimalImage(BufferedImage)} for
    * that.
    * <p/>
    * We force all rendering results into one of these two types, avoiding the
    * case where a source image is of an unsupported (or poorly supported)
    * format by Java2D causing the rendering result to end up looking terrible
    * (common with GIFs) or be totally corrupt (e.g. solid black image).
    * <p/>
    * Originally reported by Magnus Kvalheim from Movellas when scaling certain
    * GIF and PNG images.
    * 
    * @param src
    *            The source image that will be analyzed to determine the most
    *            optimal image type it can be rendered into.
    * @param width
    *            The width of the newly created resulting image.
    * @param height
    *            The height of the newly created resulting image.
    * 
    * @return a new {@link BufferedImage} representing the most optimal target
    *         image type that <code>src</code> can be rendered into.
    * 
    * @throws IllegalArgumentException
    *             if <code>width</code> or <code>height</code> are &lt; 0.
    * 
    * @see <a
    *      href="http://www.mail-archive.com/[email protected]/msg05621.html">How
    *      Java2D handles poorly supported image types</a>
    * @see <a
    *      href=
    *      "http://code.google.com/p/java-image-scaling/source/browse/trunk/src/main/java/com/mortennobel/imagescaling/MultiStepRescaleOp.java">Thanks
    *      to Morten Nobel for implementation hint</a>
    */
   protected static BufferedImage createOptimalImage(BufferedImage src, int width, int height)
    throws IllegalArgumentException {
if (width <= 0 || height <= 0)
    throw new IllegalArgumentException("width [" + width + "] and height [" + height + "] must be > 0");

return new BufferedImage(width, height, (src.getTransparency() == Transparency.OPAQUE
	? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB));
   }
 
Example 13
Project: ConvNetCL4J   File: Scalr.java   View Source Code Vote up 3 votes
/**
 * Used to create a {@link BufferedImage} with the given dimensions and the
 * most optimal RGB TYPE ( {@link BufferedImage#TYPE_INT_RGB} or
 * {@link BufferedImage#TYPE_INT_ARGB} ) capable of being rendered into from
 * the given <code>src</code>.
 * <p/>
 * This does not perform a copy of the image data from <code>src</code> into
 * the result image; see {@link #copyToOptimalImage(BufferedImage)} for
 * that.
 * <p/>
 * We force all rendering results into one of these two types, avoiding the
 * case where a source image is of an unsupported (or poorly supported)
 * format by Java2D causing the rendering result to end up looking terrible
 * (common with GIFs) or be totally corrupt (e.g. solid black image).
 * <p/>
 * Originally reported by Magnus Kvalheim from Movellas when scaling certain
 * GIF and PNG images.
 * 
 * @param src
 *            The source image that will be analyzed to determine the most
 *            optimal image type it can be rendered into.
 * @param width
 *            The width of the newly created resulting image.
 * @param height
 *            The height of the newly created resulting image.
 * 
 * @return a new {@link BufferedImage} representing the most optimal target
 *         image type that <code>src</code> can be rendered into.
 * 
 * @throws IllegalArgumentException
 *             if <code>width</code> or <code>height</code> are &lt; 0.
 * 
 * @see <a
 *      href="http://www.mail-archive.com/[email protected]/msg05621.html">How
 *      Java2D handles poorly supported image types</a>
 * @see <a
 *      href="http://code.google.com/p/java-image-scaling/source/browse/trunk/src/main/java/com/mortennobel/imagescaling/MultiStepRescaleOp.java">Thanks
 *      to Morten Nobel for implementation hint</a>
 */
protected static BufferedImage createOptimalImage(BufferedImage src,
		int width, int height) throws IllegalArgumentException {
	if (width <= 0 || height <= 0)
		throw new IllegalArgumentException("width [" + width
				+ "] and height [" + height + "] must be > 0");

	return new BufferedImage(
			width,
			height,
			(src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB
					: BufferedImage.TYPE_INT_ARGB));
}