Java: create shadow effect on image - java

I'm trying to create a shadow effect (with java) on an image.
I've seen multiple related questions and I've implemented several of the suggested solutions. Unfortunately I always have the same problem: the shadow effect repaints the entire image in gray (i.e. the shadow color) - hence the original image is not visible anymore.
Example of code I tested (based on the JIDE freely available library):
ShadowFactory sf = new ShadowFactory(2, 0.5f, Color.black);
ImageIO.write(sf.createShadow(ImageIO.read(new File("c:\\out2.png"))), "png", new File("c:\\out3.png"));
No need to says that I tested this with multiple source files (out2.png).
I'm clueless: any hint/help would be highly appreciated.

The over all theory is simple. Basically, you need to generate a mask of the image (using a AlphaComposite and fill that resulting image with the color you want (also using an AlphaComposite. This, of course, all works on the alpha channel of the image...
Once you have that mask, you need to combine the two images (overlaying the original image with the masked image)
This examples make use of JHLabs filters to supply the blur...
public class TestImageDropShadow {
public static void main(String[] args) {
new TestImageDropShadow();
}
public TestImageDropShadow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImagePane extends JPanel {
private BufferedImage background;
public ImagePane() {
try {
BufferedImage master = ImageIO.read(getClass().getResource("/Scaled.png"));
background = applyShadow(master, 5, Color.BLACK, 0.5f);
} catch (IOException ex) {
Logger.getLogger(TestImageDropShadow.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public Dimension getPreferredSize() {
return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g.drawImage(background, x, y, this);
}
}
}
public static void applyQualityRenderingHints(Graphics2D g2d) {
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
}
public static BufferedImage createCompatibleImage(int width, int height) {
return createCompatibleImage(width, height, Transparency.TRANSLUCENT);
}
public static BufferedImage createCompatibleImage(int width, int height, int transparency) {
BufferedImage image = getGraphicsConfiguration().createCompatibleImage(width, height, transparency);
image.coerceData(true);
return image;
}
public static BufferedImage createCompatibleImage(BufferedImage image) {
return createCompatibleImage(image, image.getWidth(), image.getHeight());
}
public static BufferedImage createCompatibleImage(BufferedImage image,
int width, int height) {
return getGraphicsConfiguration().createCompatibleImage(width, height, image.getTransparency());
}
public static GraphicsConfiguration getGraphicsConfiguration() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
}
public static BufferedImage generateMask(BufferedImage imgSource, Color color, float alpha) {
int imgWidth = imgSource.getWidth();
int imgHeight = imgSource.getHeight();
BufferedImage imgBlur = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2 = imgBlur.createGraphics();
applyQualityRenderingHints(g2);
g2.drawImage(imgSource, 0, 0, null);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha));
g2.setColor(color);
g2.fillRect(0, 0, imgSource.getWidth(), imgSource.getHeight());
g2.dispose();
return imgBlur;
}
public static BufferedImage generateBlur(BufferedImage imgSource, int size, Color color, float alpha) {
GaussianFilter filter = new GaussianFilter(size);
int imgWidth = imgSource.getWidth();
int imgHeight = imgSource.getHeight();
BufferedImage imgBlur = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2 = imgBlur.createGraphics();
applyQualityRenderingHints(g2);
g2.drawImage(imgSource, 0, 0, null);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, alpha));
g2.setColor(color);
g2.fillRect(0, 0, imgSource.getWidth(), imgSource.getHeight());
g2.dispose();
imgBlur = filter.filter(imgBlur, null);
return imgBlur;
}
public static BufferedImage applyShadow(BufferedImage imgSource, int size, Color color, float alpha) {
BufferedImage result = createCompatibleImage(imgSource, imgSource.getWidth() + (size * 2), imgSource.getHeight() + (size * 2));
Graphics2D g2d = result.createGraphics();
g2d.drawImage(generateShadow(imgSource, size, color, alpha), size, size, null);
g2d.drawImage(imgSource, 0, 0, null);
g2d.dispose();
return result;
}
public static BufferedImage generateShadow(BufferedImage imgSource, int size, Color color, float alpha) {
int imgWidth = imgSource.getWidth() + (size * 2);
int imgHeight = imgSource.getHeight() + (size * 2);
BufferedImage imgMask = createCompatibleImage(imgWidth, imgHeight);
Graphics2D g2 = imgMask.createGraphics();
applyQualityRenderingHints(g2);
int x = Math.round((imgWidth - imgSource.getWidth()) / 2f);
int y = Math.round((imgHeight - imgSource.getHeight()) / 2f);
g2.drawImage(imgSource, x, y, null);
g2.dispose();
// ---- Blur here ---
BufferedImage imgGlow = generateBlur(imgMask, (size * 2), color, alpha);
return imgGlow;
}
public static Image applyMask(BufferedImage sourceImage, BufferedImage maskImage) {
return applyMask(sourceImage, maskImage, AlphaComposite.DST_IN);
}
public static BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage, int method) {
BufferedImage maskedImage = null;
if (sourceImage != null) {
int width = maskImage.getWidth(null);
int height = maskImage.getHeight(null);
maskedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D mg = maskedImage.createGraphics();
int x = (width - sourceImage.getWidth(null)) / 2;
int y = (height - sourceImage.getHeight(null)) / 2;
mg.drawImage(sourceImage, x, y, null);
mg.setComposite(AlphaComposite.getInstance(method));
mg.drawImage(maskImage, 0, 0, null);
mg.dispose();
}
return maskedImage;
}
}

This is my Version:
private static Image dropShadow(BufferedImage img) {
// a filter which converts all colors except 0 to black
ImageProducer prod = new FilteredImageSource(img.getSource(), new RGBImageFilter() {
#Override
public int filterRGB(int x, int y, int rgb) {
if (rgb == 0)
return 0;
else
return 0xff000000;
}
});
// create whe black image
Image shadow = Toolkit.getDefaultToolkit().createImage(prod);
// result
BufferedImage result = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
Graphics2D g = (Graphics2D) result.getGraphics();
// draw shadow with offset
g.drawImage(shadow, 10, 0, null);
// draw original image
g.drawImage(img, 0, 0, null);
return result;
}

Related

BufferedImage black and white after scaling

After scaling BufferdImages of nation flags about 50% of all flags are displayed in black and white (not grayscale) and few do look weird, like turky:
Here's a black and white example
Here I set the flag
protected void updateFlag(BufferedImage flag){
int height = pnlFlag.getHeight();
int width = (int)(1f * flag.getWidth() / flag.getHeight() * height);
BufferedImage scaledFlag = new BufferedImage(width, height, flag.getType());
Graphics2D g2d = scaledFlag.createGraphics();
g2d.drawImage(flag, 0, 0, scaledFlag.getWidth(), scaledFlag.getHeight(), null);
g2d.dispose();
pnlFlag.flag = scaledFlag;
pnlFlag.repaint();
}
And my JPanel
class FlagPanel extends JPanel{
private BufferedImage flag;
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
if(flag == null) return;
g.drawImage(flag, 0, 0, null);
}
}
I'm pretty sure you can not just change the height and width of a Buffered Image and it will scale for you.
Try using getScaledInstance() like in this question.
The code bellow works fine, but you need to call the repaint method because the getScaledInstance method take a time to generate the scaloned image.
public class Main extends JFrame {
private ImageIcon ico;
private boolean resize = true;
private Image scale;
public Main() {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
ico = new ImageIcon("image.jpg");
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D gg = (Graphics2D) g;
if (!resize) {
g.drawImage(ico.getImage(), 0, 0, null);
} else {
if (scale == null) {
scale = ico.getImage().getScaledInstance(ico.getIconWidth() / 2, ico.getIconHeight() / 2, Image.SCALE_SMOOTH);
}
g.drawImage(scale, 0, 0, null);
// gg.scale(0.5, 0.5);
// gg.drawImage(ico.getImage(), 0, 0, null);
}
}
public static void main(String[] args) {
Main m = new Main();
m.setSize(600, 600);
m.setVisible(true);
}
}

Display the whole image using DrawImage() after Image rotation

I am rotating and scaling the image using AffineTransform. When I display the image using Graphics2D.drawImage() the whole image does not get displayed so I am calling the AffineTransform.translate method.
Here is the code I have currently written:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Dimension dim = getPreferredSize();
int x = (getWidth() - image.getWidth(null)) / 2;
int y = (getHeight() - image.getHeight(null)) / 2;
double angle = Math.toRadians(rotateAngle);
AffineTransform identity = new AffineTransform();
identity.scale(scale, scale);
identity.translate(x,y);
AffineTransform at = new AffineTransform();
setPreferredSize(new Dimension((int)(identity.getTranslateX()+(image.getWidth(null)*scale)),(int)(identity.getTranslateY()+(image.getHeight(null)*scale))));
at.setTransform(identity);
at.rotate(angle);
g2d.transform(at);
g2d.drawImage(image, 0, 0, this);
g2d.dispose();
}
The translate method sometimes displays the whole image and sometimes does not depending on the image size and rotating angle. Is there anyway to make sure the whole image gets displayed after a rotate.
I had a look at this previous asked question:
Java2D Image Rotation Issue
but the solution posted there gave the same problem for me.
I finally figured out a way to do this for 90 degrees, it will not work for other degrees.
void rotate90(){
if(image!=null){
int w = image.getWidth(null); //the Width of the original image
int h = image.getHeight(null);//the Height of the original image
if(w>h){
BufferedImage dimg = new BufferedImage(w, w, BufferedImage.TYPE_3BYTE_BGR );
Graphics2D g = dimg.createGraphics();
g.translate(-(w-h), 0);
g.rotate(Math.toRadians(90), w/2, w/2);
g.drawImage(image, 0, 0,null);
BufferedImage bimg = new BufferedImage(h, w, BufferedImage.TYPE_3BYTE_BGR );
Graphics2D g2 = (Graphics2D)bimg.getGraphics();
g2.drawImage(dimg,0,0,h,w,0,0,h,w,null);
dimg.flush();
dimg=null;
image = createImage(bimg.getSource());
bimg.flush();
bimg= null;
}
else{
BufferedImage dimg = new BufferedImage(h, h, BufferedImage.TYPE_3BYTE_BGR );
Graphics2D g = dimg.createGraphics();
g.translate(-(w-h), 0);
g.rotate(Math.toRadians(90), w/2, w/2);
g.drawImage(image, 0, 0,null);
BufferedImage bimg = new BufferedImage(h, w, BufferedImage.TYPE_3BYTE_BGR );
Graphics2D g2 = (Graphics2D)bimg.getGraphics();
g2.drawImage(dimg,0,0,h,w,0,0,h,w,null);
dimg.flush();
dimg=null;
image = createImage(bimg.getSource());
bimg.flush();
bimg= null;
}
}
}
void rotateClockWise(){
if(image!=null){
rotate90();
setPanelsize();
revalidate();
repaint();
}
}
sometimes displays the whole image and sometimes does not depending on the image size and rotating angle
You need to recalculate the size of the rotated image. Here is an example of how to do that:
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.*;
public class Rotation
{
BufferedImage image;
JLabel label;
public Rotation(BufferedImage image)
{
this.image = image;
}
private BufferedImage getImage(double theta)
{
// Determine the size of the rotated image
double cos = Math.abs(Math.cos(theta));
double sin = Math.abs(Math.sin(theta));
double width = image.getWidth();
double height = image.getHeight();
int w = (int)(width * cos + height * sin);
int h = (int)(width * sin + height * cos);
// Rotate and paint the original image onto a BufferedImage
BufferedImage out = new BufferedImage(w, h, image.getType());
Graphics2D g2 = out.createGraphics();
g2.setPaint(UIManager.getColor("Panel.background"));
g2.fillRect(0,0,w,h);
double x = w/2;
double y = h/2;
AffineTransform at = AffineTransform.getRotateInstance(theta, x, y);
x = (w - width)/2;
y = (h - height)/2;
at.translate(x, y);
g2.drawRenderedImage(image, at);
g2.dispose();
return out;
}
private JLabel getLabel()
{
ImageIcon icon = new ImageIcon(image);
label = new JLabel(icon);
label.setHorizontalAlignment(JLabel.CENTER);
return label;
}
private JSlider getSlider()
{
final JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 360, 0);
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
int value = slider.getValue();
BufferedImage bi = getImage(Math.toRadians(value));
label.setIcon(new ImageIcon(bi));
}
});
return slider;
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
String path = "mong.jpg";
ClassLoader cl = Rotation.class.getClassLoader();
BufferedImage bi = ImageIO.read(cl.getResourceAsStream(path));
Rotation r = new Rotation(bi);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(r.getLabel()));
f.getContentPane().add(r.getSlider(), "South");
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
catch(IOException e)
{
System.out.println(e);
}
}
});
}
}
Not sure how the scaling will affect this. Maybe you can just multiply the width/height by the scaling factor?

How to draw a Round rectangle in java with normal rectangle outline

For my java application i need a Round rectangle with an outline that looks like a normal rectangle, like this
I know you can do that by drawing a normal rectangle and a RoundRect inside it but i don't want to draw a RoundRect inside it because I want to draw something else in it.
So a round rect with normal corners. How do I draw that in Java?
The problem is that the rectangle looks like this if I use layers:
The corners are filled up with the wrong color. How do I prevent that?
I can think of two approaches. The first is to generate a Shape that represents the square outter edge and the rounded inner edge.
The second would be to use a AlphaComposite to generate a masked result.
public class TestMask {
public static void main(String[] args) {
new TestMask();
}
public TestMask() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MaskedPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MaskedPane extends JPanel {
public MaskedPane() {
setBackground(Color.RED);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage outter = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = outter.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
BufferedImage inner = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
g2d = inner.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fillRoundRect(10, 10, getWidth() - 20, getHeight() - 20, 20, 20);
g2d.dispose();
BufferedImage masked = applyMask(outter, inner, AlphaComposite.DST_OUT);
g.drawImage(masked, 0, 0, this);
}
public BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage, int method) {
BufferedImage maskedImage = null;
if (sourceImage != null) {
int width = maskImage.getWidth();
int height = maskImage.getHeight();
maskedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D mg = maskedImage.createGraphics();
int x = (width - sourceImage.getWidth()) / 2;
int y = (height - sourceImage.getHeight()) / 2;
mg.drawImage(sourceImage, x, y, null);
mg.setComposite(AlphaComposite.getInstance(method));
mg.drawImage(maskImage, 0, 0, null);
mg.dispose();
}
return maskedImage;
}
public BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage) {
return (BufferedImage) applyMask(sourceImage, maskImage, AlphaComposite.DST_IN);
}
}
}
Updated with Shape example
Finally had time to bang one out...
public class TestMask {
public static void main(String[] args) {
new TestMask();
}
public TestMask() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ShapedPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ShapedPane extends JPanel {
public ShapedPane() {
setBackground(Color.GREEN);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fill(new RounedFrame(getWidth(), getHeight(), 10, 20));
g2d.dispose();
}
}
public class RounedFrame extends Path2D.Float {
public RounedFrame(float width, float height, float thickness, float radius) {
moveTo(0, 0);
lineTo(width, 0);
lineTo(width, height);
lineTo(0, height);
lineTo(0, 0);
float innerWidth = width - thickness;
float innerHeight = height - thickness;
moveTo(thickness + radius, thickness);
lineTo(innerWidth - radius, thickness);
curveTo(innerWidth, thickness, innerWidth, thickness, innerWidth, thickness + radius);
lineTo(innerWidth, innerHeight - radius);
curveTo(innerWidth, innerHeight, innerWidth, innerHeight, innerWidth - radius, innerHeight);
lineTo(thickness + radius, innerHeight);
curveTo(thickness, innerHeight, thickness, innerHeight, thickness, innerHeight - radius);
lineTo(thickness, thickness + radius);
curveTo(thickness, thickness, thickness, thickness, thickness + radius, thickness);
closePath();
setWindingRule(WIND_EVEN_ODD);
}
}
}
Updated
From a comment by Andrew, you could simplify the use of the shape example by using Area
You could replace the paintComponent from the above example with this one...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Area area = new Area(new Rectangle(0, 0, getWidth(), getHeight()));
area.subtract(new Area(new RoundRectangle2D.Float(10, 10, getWidth() - 20, getHeight() - 20, 20, 20)));
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fill(area);
g2d.dispose();
}
Which is much simpler :D
Something like:
paintComponent(Graphics g) {
//If you want more: Graphics2D g2 = (Graphics2D) g;
Rect rect = getBounds();
g.setColor(Color.BLACK);
g.fillRect(rect.x, rect,y, rect.width, rect.height);
rect.grow(-4, -4);
g.setColor(getBackground());
g.fillRoundRect(rect.x, rect,y, rect.width, rect.height, 5, 5);
}
E.G.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
class CustomBorderWithContent {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
int w = 200;
int h = 100;
int pad = 4;
BufferedImage img = new BufferedImage(
w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Ripped/adapted from Joop's answer
g.setColor(Color.BLACK);
g.fillRect(0, 0, w, h);
g.setColor(Color.ORANGE);
g.fillRoundRect(pad, pad, w-2*pad, h-2*pad, 25, 25);
// Now..
g.setColor(Color.BLUE);
g.drawString("Something else..", 20, 25);
g.dispose();
JOptionPane.showMessageDialog(
null, new JLabel(new ImageIcon(img)));
}
};
SwingUtilities.invokeLater(r);
}
}

Translucent JFrame border JDK 7

I was asking question about Translucent JFrame border (see here) and I got very good answers, but unfortunatelly, given answers work perfectly only on JDK 6, but not 7. Any ideas how to make it work with JDK 7?
In JDK 6 it looks like this:
And JDK 7:
And my code looks like this:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.border.AbstractBorder;
public class ShadowBorder extends AbstractBorder {
private static final int RADIUS = 30;
private static BufferedImage shadowTop;
private static BufferedImage shadowRight;
private static BufferedImage shadowBottom;
private static BufferedImage shadowLeft;
private static BufferedImage shadowTopLeft;
private static BufferedImage shadowTopRight;
private static BufferedImage shadowBottomLeft;
private static BufferedImage shadowBottomRight;
private static boolean shadowsLoaded = false;
public ShadowBorder() {
if (!shadowsLoaded) {
try {
shadowTop = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-top.png"));
shadowRight = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-right.png"));
shadowBottom = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-bottom.png"));
shadowLeft = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-left.png"));
shadowTopLeft = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-top-left.png"));
shadowTopRight = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-top-right.png"));
shadowBottomLeft = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-bottom-left.png"));
shadowBottomRight = ImageIO.read(getClass().getResource("/cz/vutbr/fit/assets/shadow-bottom-right.png"));
shadowsLoaded = true;
} catch (IOException ex) {
Logger.getLogger(ShadowBorder.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public boolean isBorderOpaque() {
return false;
}
#Override
public Insets getBorderInsets(Component c) {
return new Insets(RADIUS, RADIUS, RADIUS, RADIUS);
}
#Override
public Insets getBorderInsets(Component c, Insets insets) {
insets.top = RADIUS;
insets.left = RADIUS;
insets.bottom = RADIUS;
insets.right = RADIUS;
return insets;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_ATOP, 1f));
int recWidth = width - (2 * RADIUS);
int recHeight = height - (2 * RADIUS);
int recX = width - RADIUS;
int recY = height - RADIUS;
//edges
g2d.drawImage(shadowTop.getScaledInstance(recWidth, RADIUS, Image.SCALE_REPLICATE), RADIUS, 0, null);
g2d.drawImage(shadowRight.getScaledInstance(RADIUS, recHeight, Image.SCALE_REPLICATE), recX, RADIUS, null);
g2d.drawImage(shadowBottom.getScaledInstance(recWidth, RADIUS, Image.SCALE_REPLICATE), RADIUS, recY, null);
g2d.drawImage(shadowLeft.getScaledInstance(RADIUS, recHeight, Image.SCALE_REPLICATE), 0, RADIUS, null);
//corners
g2d.drawImage(shadowTopLeft, 0, 0, null);
g2d.drawImage(shadowTopRight, recX, 0, null);
g2d.drawImage(shadowBottomLeft, 0, recY, null);
g2d.drawImage(shadowBottomRight, recX, recY, null);
}
}
Thanks a lot!
I've just solved my problem. The problem was, that JDK 7 implements AWTUtilities.setWindowOpaque() method from JDK6 in setBackground() method and I was (NetBeans did :-)) setting default background for JFrame in different place, so setting background to new Color(0, 0, 0, 0); makes JFrame transparent and all goes well now.
For whoever stumbles upon this thread and wants his own transparent window, I devised this example. With how little information is available on the web, I almost had to break a leg to come up with something just works, and doesn't use image files or anything. (Combined from different examples on this site)
public class GradientTranslucentWindowDemo
{
public static void main(String[] args)
{
// Create the GUI on the event-dispatching thread
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
final JFrame f = new JFrame("Per-pixel translucent window");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.setBackground(new Color(0, 0, 0, 0));
final BufferedImage backrgoundImage = makeBackrgoundImage(400, 400);
JPanel panel = new JPanel()
{
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (g instanceof Graphics2D)
{
g.drawImage(backrgoundImage, 0, 0, null);
}
}
};
panel.setOpaque(false);
f.setContentPane(panel);
f.setLayout(new GridBagLayout()); // Centers the button
f.add(new JButton(new AbstractAction("Close")
{
#Override
public void actionPerformed(ActionEvent e)
{
f.dispose();
}
}));
f.setBounds(100, 100, 400, 400);
f.setVisible(true);
}
});
}
static BufferedImage makeBackrgoundImage(int w, int h)
{
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
// Draw something transparent
Graphics2D g = img.createGraphics();
g.setPaint(new RadialGradientPaint(new Point2D.Float(w / 2, h / 2), (w + h) / 4, new float[]{0, 1}, new Color[]{Color.RED, new Color(1f, 0, 0, 0)}));
g.fillRect(0, 0, w, h);
g.setPaint(Color.RED);
g.drawRect(0, 0, w - 1, h - 1);
g.dispose();
return img;
}
}

How to resize the buffered image n graphics 2d in java?

int width = 175;
Graphics2D gb = (Graphics2D) g;
bufferedimage = (BufferedImage) createImage(width, width);
Graphics2D graphics = bufferedimage.createGraphics();
graphics.setColor(/*this.getBackground()*/Color.red);
graphics.fillRect(0, 0, width, width);
hi i have the the buffered with big size...i have to resize the bufferd image...plz can u anyone help me?
public BufferedImage scaleImage(BufferedImage img, int width, int height,
Color background) {
int imgWidth = img.getWidth();
int imgHeight = img.getHeight();
if (imgWidth*height < imgHeight*width) {
width = imgWidth*height/imgHeight;
} else {
height = imgHeight*width/imgWidth;
}
BufferedImage newImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = newImage.createGraphics();
try {
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setBackground(background);
g.clearRect(0, 0, width, height);
g.drawImage(img, 0, 0, width, height, null);
} finally {
g.dispose();
}
return newImage;
}
UPDATE: different algorithms
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
public enum Resizer {
NEAREST_NEIGHBOR {
#Override
public BufferedImage resize(BufferedImage source,
int width, int height) {
return commonResize(source, width, height,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
},
BILINEAR {
#Override
public BufferedImage resize(BufferedImage source,
int width, int height) {
return commonResize(source, width, height,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
}
},
BICUBIC {
#Override
public BufferedImage resize(BufferedImage source,
int width, int height) {
return commonResize(source, width, height,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
}
},
PROGRESSIVE_BILINEAR {
#Override
public BufferedImage resize(BufferedImage source,
int width, int height) {
return progressiveResize(source, width, height,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
}
},
PROGRESSIVE_BICUBIC {
#Override
public BufferedImage resize(BufferedImage source,
int width, int height) {
return progressiveResize(source, width, height,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
}
},
AVERAGE {
#Override
public BufferedImage resize(BufferedImage source,
int width, int height) {
Image img2 = source.getScaledInstance(width, height,
Image.SCALE_AREA_AVERAGING);
BufferedImage img = new BufferedImage(width, height,
source.getType());
Graphics2D g = img.createGraphics();
try {
g.drawImage(img2, 0, 0, width, height, null);
} finally {
g.dispose();
}
return img;
}
};
public abstract BufferedImage resize(BufferedImage source,
int width, int height);
private static BufferedImage progressiveResize(BufferedImage source,
int width, int height, Object hint) {
int w = Math.max(source.getWidth()/2, width);
int h = Math.max(source.getHeight()/2, height);
BufferedImage img = commonResize(source, w, h, hint);
while (w != width || h != height) {
BufferedImage prev = img;
w = Math.max(w/2, width);
h = Math.max(h/2, height);
img = commonResize(prev, w, h, hint);
prev.flush();
}
return img;
}
private static BufferedImage commonResize(BufferedImage source,
int width, int height, Object hint) {
BufferedImage img = new BufferedImage(width, height,
source.getType());
Graphics2D g = img.createGraphics();
try {
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
g.drawImage(source, 0, 0, width, height, null);
} finally {
g.dispose();
}
return img;
}
};

Categories

Resources