Cropping an image using Java - java

How to crop images in Java? I currently have this class for image manipulation.
The main method with the run method:
public static void main(String[] args) {
GameProject gp = new GameProject();
gp.run();
}
public void run(){
s = new Screen();
try {
DisplayMode dm = s.findFirstCompatibleMode(modes);
s.setFullscreen(dm);
Fonts f = new Fonts(); //Checks if certain fonts exsist, if not install them.
Images i = new Images();
try {
i.draw("H:\\Dropbox\\Dropbox\\GameProject\\src\\Resources\\brock.png", 200, 200);
Thread.sleep(50000);
} catch (Exception e) {}
} finally {
s.restoreScreen();
}
}
Images class:
package Handlers;
import javax.swing.ImageIcon;
import java.awt.*;
/**
*
* #author Steven
*/
public class Images {
/**
* #param args the command line arguments
*/
private Screen s;
public void draw(String name, int x, int y) { //Draws the image
s = new Screen();
Graphics2D g = s.getGraphics();
draws(g, name, x, y, getWidth(name), getHeight(name));
}
public void drawA(String name, int x, int y){ //Draws the image, allows for a more advanced image manipulation
s = new Screen();
Graphics2D g = s.getGraphics();
draws(g, name, x, y, getWidth(name), getHeight(name));
}
public void draws(Graphics g, String name, int x, int y, int w, int h) { //Draws and updates the screen
s = new Screen();
g.drawImage(new ImageIcon(name).getImage(), x, y, w, h, null);
s.update();
}
public int getWidth(String name) { //Gets the image width
return new ImageIcon(name).getIconWidth();
}
public int getHeight(String name) { //Gets the images height
return new ImageIcon(name).getIconHeight();
}
}
Any help would be appreciated.

You can use CropImageFilter to crop images. Also, take a look at the java.awt.image package, it does have a lot of image manipulation routines.

I have used this in my own project :-
public boolean CropImage(int cropHeight,int cropWidth,int windowLeft,int windowTop,File srcFile,String destDirectory,String destFilename,int commonPadding,String fileFormat,HttpServletRequest request)throws IOException{
boolean isOkResolution=false;
try {
String dirPath=request.getRealPath("")+"/"+destDirectory;
File f=new File(dirPath);
if(!f.isDirectory()){
f.mkdir();
}
String destpath=dirPath+"/"+destFilename;
File outputFile=new File(destpath);
FileInputStream fis=new FileInputStream(srcFile);
BufferedImage bimage=ImageIO.read(fis);
System.out.println("Image Origilnal Height=="+bimage.getHeight());
BufferedImage oneimg=new BufferedImage(cropHeight,cropWidth,bimage.getType());
Graphics2D gr2d=oneimg.createGraphics();
isOkResolution=gr2d.drawImage(bimage,0,0,cropWidth,cropHeight,windowLeft-commonPadding,windowTop-commonPadding,(windowLeft+cropWidth)-commonPadding,(windowTop+cropHeight)-commonPadding,null);
gr2d.dispose();
ImageIO.write(oneimg,fileFormat,outputFile);
} catch (FileNotFoundException fe) {
System.out.println("No File Found =="+fe);
} catch(Exception ex){
System.out.println("Error in Croping File="+ex);
ex.printStackTrace();
}
return isOkResolution;
}
This method will help you to crop the image.Its working fine for my project.Hope it will help you out.

Related

reading Image fails: Java

Im coding a liitle game for java and want to make the Player look like a rocket, so i try to load the miage and then draw it on Java awt canvas.
Unfortunately i kepp gettin an IOException, but i dont get why... is the image some how wrong?
Thank you ver helpiNg me in advance and here`s the code:
(the image is in the same package as the Player class)
public class Player extends GameEntity {
private BufferedImage img;
public Player(int x, int y, ID id){
super(x, y , id);
}
BufferedImage loadImage(String fileName) {
BufferedImage bi = null;
//System.err.println("....setimg...." + fileName);
try {
bi = ImageIO.read(new File(fileName));
} catch (IOException e) {
e.printStackTrace();
System.out.println("Image could not be read");
System.exit(1);
}
return bi;
}
#Override
public void tick() {
x += velX;
y += velY;
}
#Override
public void render(Graphics graphics) {
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
BufferedImage rocketImage = loadImage("rocket.png");
Graphics2D g2d = (Graphics2D) graphics;
g2d.drawImage(rocketImage, at, null);
}
}

How to paint GUI with Binary Image Processing?

I'm working on image processing but I can't find a way to paint GUI RGB with binary image reading. I'm stuck with paintComponent area.
I can read file but cant paint RGB values to GUI. Can somebody guide me please?
This is what I have done so far:
private int ws;
private FileInputStream fis;
mybin(){
try {
fis = new FileInputStream("mybin.bin");
String mn = getMagicNumber();
System.out.println(mn);
skipWhitespace();
int width = readNumber();
System.out.println(width);
skipWhitespace();
int height = readNumber();
System.out.println(height);
skipWhitespace();
int maxNum = readNumber();
System.out.println(maxNum);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e2) {}
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600,600);
this.setVisible(true);
}
private String getMagicNumber() {
byte [] magicNum = new byte[2];
try {
fis.read(magicNum);
} catch (IOException e) {
e.printStackTrace();
}
return new String(magicNum);
}
private void skipWhitespace() {
try {
ws = fis.read();
while(Character.isWhitespace(ws))
ws = fis.read();
} catch (IOException e) {
e.printStackTrace();
}
}
private int readNumber() {
String wstr = "";
try {
while(!Character.isWhitespace(ws)) {
//while(Character.isDigit(ws))
wstr = wstr + (ws-'0'/*48*/);
ws = fis.read();
}
}catch(IOException e2) {}
System.out.println(wstr);
return Integer.parseInt(wstr);
}
class DrawingPanel extends JPanel{
#Override
public void paintComponent(Graphics g) {
}
}
public static void main(String [] args) {
new mybin();
}
}
If you have a data structure to hold RGB values and want to paint them on the screen:
First you should create an image of them, first. Something like this:
// Create an image, with given dimensions, and RGB palette...
final BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB);
// Paint the RGB values (EG from arrays) to the image
for (int x = 0; x < width; ++x)
for (int y = 0; y < height; ++y)
{
// Convert the R,G,B values to a single int
final int rgb = r[x,y]*0x10000 + g[x,y]*1x100 + b[x,y];
// Color the pixel...
image.setRGB(x, y, rgb);
}
Then display it on your GUI.
This could be done, creating a special component, and performing painting, see c0der's answer.
Or you could just create an Icon, and add it to any JLabel:
label.setIcon(new ImageIcon(image));
Painting a BufferedImage can be as simple as:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImageFrame extends javax.swing.JFrame {
public ImageFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new GraphicsPanel());
pack();
setVisible(true);
}
public static void main(final String[] args){
new ImageFrame();
}
}
class GraphicsPanel extends JPanel {
private BufferedImage image;
//always use publicly accessible resources when posting mcve
private final String imagePath = "https://upload.wikimedia.org/wikipedia/commons/3/3f/Crystal_Project_bug.png";
GraphicsPanel(){
try {
image = ImageIO.read(new URL(imagePath)); //or image = ImageIO.read(new File(...));
} catch(final IOException e) {e.printStackTrace(); }
setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
}
#Override
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}

Java Image Panel File Import

I am currently having an issue with my code that it won't import an image from the file dialog. Basically it's meant to import the image when selected and place it on an Image Panel which is implemented.
Here is the code I have written for the File Import
FileDialog dialog = new FileDialog((Frame)null, "Select File to Open");
dialog.setMode(FileDialog.LOAD);
dialog.setVisible(true);
String file = dialog.getFile();
imageP.readImage(file);
imageP.repaint();
Here is the Image Panel Class
class ImagePanel extends JPanel
{
int numCols, numRows;
BufferedImage image = null;
private final int xOffset = 0;
private final int yOffset = 0;
public ImagePanel()
{
readImage("");
}
public void readImage(String filename)
{
try {
image = ImageIO.read(new File(filename));
numRows = image.getHeight();
numCols = image.getWidth();
}
catch( IOException e )
{
e.printStackTrace();
}
}
public void paintComponent( Graphics g )
{
Graphics2D g2 = (Graphics2D)g;
g2.clearRect(0, 0, this.getWidth(), this.getHeight());
if (image != null)
{
g2.drawImage( image, xOffset, yOffset, null );
}
}
}
I currently get an IIOException which says can't read file at the moment.
If anyone can help me with this issue that would be great.

Why does my BlueJ jar file load some images, but not others?

I used some of the information around this site to find out to use URLs to get images into a jar file; which I want to be able to be used alone. But when I make the jar file with BlueJ, only some images show up.
Its a blackjack game, and only the table canvas shows up, while no cards ever do. Here's the code:
THIS WORKS (the table):
public class TableComponent extends JLabel{
BufferedImage table;
public TableComponent(){
URL finalTable = getClass().getResource("blackjackTableCanvas.jpg");
try {
table = ImageIO.read(finalTable);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
g2.drawImage(table, 0, 0, null);
}...}
but this does not (the cards):
public class CardRender2 extends JComponent{
BufferedImage image;
String val;
String suit;
String filename;
public CardRender2(Card card) {
this.val = card.value.face;
this.suit = card.suit.toString();
filename = this.fetchCardFileLabel();
URL cardview = getClass().getResource("\\card deck\\" + filename + ".png");
try {
image = ImageIO.read(cardview);
} catch (IOException e) {
e.printStackTrace();
}
}
public CardRender2(){
this.val = null;
this.suit = null;
filename = "DEALER_FIRST_CARD";
URL cardview = getClass().getResource("\\card deck\\DEALER_FIRST_CARD.png");
try {
image = ImageIO.read(cardview);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
g2.drawImage(image, 0, 0, null);
}...}
my cards are in a folder in the directory I try to import into BlueJ, whereas the table is in the directory root. There are 53 cards in there (incl dealer hidden card) and I'd rather not put all of then in the root. I tried to implement them similarly. How can I do this?
looks like changing from
URL cardview = getClass().getResource("\\card deck\\DEALER_FIRST_CARD.png");
to
URL cardview = getClass().getResource("card deck/DEALER_FIRST_CARD.png");
did the trick.

Why is this Robot code to take a screenshot not working when the computer is locked?

I am using the Robot class to take a screenshot of the desktop:
Robot objRobot = null;
try {
objRobot = new Robot();
} catch(Exception ex) {
}
BufferedImage objBufferedImage = objRobot.createScreenCapture(objRectArea);
The problem is that when my computer is locked the image comes up as black. That is, what is displayed on the desktop is not captured. I want the screenshot to display the desktop even when my computer is locked. How can I do this? I would prefer a solution that still uses Robot.
Try this
public class Main {
private Robot robot = new Robot();
public Main() throws AWTException, IOException {
int x = 800;
int y = 800;
int width = 200;
int height = 200;
imageCapture(x, y, width, height);
}
private void imageCapture(int x, int y, int width, int height) throws IOException {
Rectangle area = new Rectangle(x, y, width, height);
BufferedImage bufferedImage = robot.createScreenCapture(area);
//remove next line if u do not want file.png saved
ImageIO.write(bufferedImage, "png", new File("file.png"));
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws AWTException, IOException {
new Main();
}/**
* #return the robot
*/
public Robot getRobot() {
return robot;
}
/**
* #param robot the robot to set
*/
public void setRobot(Robot robot) {
this.robot = robot;
}
}
Makes file.png in project too

Categories

Resources