code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Saw here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Saw extends Trap
{
private int distance;
private boolean goingBack;
private int movement;
private Timer aniTimer=new Timer();
public Saw(int x,int del,int iniD,int d)
{
super(x,del,iniD);
distance=d;
movement=0;
damage=20;
goingBack=true;
setImage(new GreenfootImage("saw.png"));
}
public void act()
{
timer.tick();
activeTimer.tick();
aniTimer.tick();
GameWorld world=(GameWorld)getWorld();
setLocation(world.getScrollx()+360+posX+movement,getY());
if(active==true || !activeTimer.wait(initialDelay))
activeImage();
if(active==false)
return;
if(!aniTimer.wait(50))
turn(45);
if(goingBack==true)
{
if(posX+movement>posX+distance)
{
if(!timer.wait(delay))
goingBack=false;
}else
movement++;
}
else
{
if(posX+movement<posX-distance)
{
if(!timer.wait(delay))
goingBack=true;
}else
movement--;
}
Player player=getPlayer();
if(isTouchingPlayer())
player.getHurt(damage);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
import java.util.List;
/**
* Write a description of class TestWorld here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class GameWorld extends World
{
private int scrollx;
private int terrainNum;
private int max;
private int min;
private int level;
private int lastLevel;
private int helpIndex=0;
private int spawnPoint=0;
private int animation;
private Screen screen=new Screen();
private Player player;
private Whip whip;
private CollisionBox colDown;
private CollisionBox colPlayer;
private CollisionBox colRight;
private CollisionBox colLeft;
private HealthBar healthbar;
private Lives lives;
private boolean isWorldAnimationPlaying;
private boolean playedAnimation;
private boolean debug=false;
private boolean playedSound;
private boolean levelChanged=false;
private Timer rockSpawn1=new Timer();
private Timer rockSpawn2=new Timer();
private Timer rockSpawn3=new Timer();
private Timer rockSpawn4=new Timer();
private GreenfootSound[] sound=new GreenfootSound[1];
private GreenfootImage[] ground;
private GreenfootImage[] ledge;
private GreenfootImage[] background;
/**
* Constructor for objects of class TestWorld.
*
*/
public GameWorld()
{
// Create a new world with 720x400 cells with a cell size of 1x1 pixels.
super(720, 400, 1, false);
scrollx = 0;
terrainNum= 1;
max= 360;
min= -360;
level=1;
lastLevel=0;
player=new Player();
whip=new Whip(player);
colDown=new CollisionBox(player,0,65,10,10);
colPlayer=new CollisionBox(player,0,0,34,90);
colRight=new CollisionBox(player,40,0,10,10);
colLeft=new CollisionBox(player,-40,0,10,10);
healthbar=new HealthBar();
lives=new Lives();
Greenfoot.setSpeed(50);
isWorldAnimationPlaying=false;
playedAnimation=false;
playedSound=false;
setBackground(new GreenfootImage("menu.png"));
//prepare();
mainMenu();
setPaintOrder(Screen.class,GUI.class,Lives.class,HealthBar.class,CollisionBox.class,Player.class,Whip.class,Boulder.class,Ground.class);
setActOrder(Player.class,Whip.class);
sound[0]=new GreenfootSound("level_clear.mp3");
makeImages();
}
/**
* Prepare the world for the start of the program. That is: create the initial
* objects and add them to the world.
*/
private void prepare()
{
makeImages();
removeObjects(getObjects(Trap.class));
removeObjects(getObjects(Ground.class));
removeObjects(getObjects(Background.class));
removeObjects(getObjects(Ledge.class));
removeObjects(getObjects(GUI.class));
addObject(player, getWidth()/2, 260);
addObject(whip, 0, 0);
addObject(colDown,getWidth()/2,getHeight()/2);
addObject(colPlayer,getWidth()/2,getHeight()/2);
addObject(colRight,getWidth()/2,getHeight()/2);
addObject(colLeft,getWidth()/2,getHeight()/2);
addObject(healthbar,0,0);
addObject(lives,40,60);
addObject(new GUI(),70,60);
addObject(new Ground(-2),getWidth()/2,getHeight()/2);
addObject(new Ground(-1),getWidth()/2,getHeight()/2);
addObject(new Ground(0),getWidth()/2,getHeight()/2);
addObject(new Ground(1),getWidth()/2,getHeight()/2);
addObject(new Ground(2),getWidth()/2,getHeight()/2);
addObject(new Ground(3),getWidth()/2,getHeight()/2);
addObject(new Background(-1),getWidth()/2,getHeight()/2);
addObject(new Background(0),getWidth()/2,getHeight()/2);
addObject(new Background(1),getWidth()/2,getHeight()/2);
addObject(new Background(2),getWidth()/2,getHeight()/2);
addObject(new Ledge(-1),getWidth()/2,getHeight()/2);
addObject(new Ledge(0),getWidth()/2,getHeight()/2);
addObject(new Ledge(1),getWidth()/2,getHeight()/2);
addObject(new Ledge(2),getWidth()/2,getHeight()/2);
scrollx = 0;
terrainNum= 1;
max= 360;
min= -360;
switch(level)
{
case -1:
spawnPoint=0;
//new Trap(positionX,delay between objects/main motion, initial delay to start moving);
//new Rock(positionX,delay between rock, initial delay to start spawning rocks,skin type);
addObject(new Rock(250,800,0,0),0,0);
addObject(new Rock(300,800,400,0),0,0);
addObject(new Rock(350,800,800,0),0,0);
addObject(new Rock(400,800,1200,0),0,0);
//new Spikes(positionX,delay between pop ups, initial delay to start moving);
addObject(new Spikes(200,800,0),0,0);
//new Wall(positionX,delay spent on lowest/highest point, initial delay to start moving, highest yPos,lowest yPos, skin);
addObject(new Wall(-50,800,0,100,getHeight()-100,0),0,-100);
addObject(new Wall(-150,800,1200,100,getHeight()-100,0),0,-100);
addObject(new Wall(-250,800,2400,100,getHeight()-100,0),0,-100);
addObject(new Wall(-350,800,3600,100,getHeight()-100,0),0,-100);
//new Saw(positionX,delay spent on edges of the trayectory, initial delay to start moving, trayectory length);
addObject(new Saw(200,0,0,100),0,200);
addObject(new Saw(200,1000,0,100),0,100);
addObject(new Scythe(-600,300,0),-100,0-20);
break;
case 1:
spawnPoint=0;
setBackground(new GreenfootImage("world_jungle.png"));
addObject(new Rock(480,800,0,1),0,0);
addObject(new Rock(750,800,400,1),0,0);
addObject(new Rock(2400,800,0,1),0,0);
addObject(new Rock(2900,800,400,1),0,0);
addObject(new Rock(5700,800,0,2),0,0);
addObject(new SnakeSpawner(1180,5000,0),0,0);
addObject(new SnakeSpawner(2600,4000,0),0,0);
addObject(new SnakeSpawner(6000,7000,0),0,0);
addObject(new Spikes(6100,1800,400),0,0);
addObject(new Spikes(6150,1800,800),0,0);
addObject(new Spikes(6200,1800,1200),0,0);
addObject(new Spikes(6250,1800,1600),0,0);
addObject(new Spikes(6300,1800,2000),0,0);
addObject(new Spikes(6350,1800,2400),0,0);
addObject(new Spikes(6400,1800,2800),0,0);
addObject(new Spikes(6450,1800,3200),0,0);
addObject(new BoulderSpawner(5000,2000,0,1,20,2),0,0);
addObject(new Wall(5310,1200,0,50,getHeight(),1),0,-100);
addObject(new Wall(5410,800,4800,50,230,1),0,-100);
addObject(new Wall(5518,1200,2400,50,getHeight(),1),0,-100);
break;
case 2:
spawnPoint=380;
scrollx=380;
setBackground(new GreenfootImage("world_mountain.png"));
default:
break;
}
}
public void mainMenu()
{
removeObjects(getObjects(null));
setBackground(new GreenfootImage("menu.png"));
level=0;
helpIndex=0;
addObject(new Play(360,233),360,233);
addObject(new Help(360,350),360,350);
addObject(new Scores(130,350),130,350);
addObject(new Credits(590,350),590,350);
}
public void play()
{
player.reset();
removeObjects(getObjects(null));
level=1;
prepare();
}
public void showCredits()
{
}
public void showScores()
{
removeObjects(getObjects(null));
setBackground(new GreenfootImage("scoreboard.png"));
addObject(new Return(80,40),80,40);
addObject(new ScoreBoard(720,400),getWidth()/2,getHeight()/2);
}
public void showHelp()
{
removeObjects(getObjects(null));
helpIndex=0;
setBackground(new GreenfootImage("help_b0.png"));
addObject(new Return(80,40),80,40);
addObject(new Next(360,getHeight()-20),360,getHeight()-20);
Greenfoot.delay(20);
}
public void nextPage()
{
helpIndex++;
if(helpIndex>=5)
{
mainMenu();
return;
}
setBackground(new GreenfootImage("help_b"+helpIndex+".png"));
}
public void act()
{
if(scrollx<=min)
{
terrainNum--;
max-=getWidth();
min-=getWidth();
}
if(scrollx>=max)
{
terrainNum++;
max+=getWidth();
min+=getWidth();
}
switch(level)
{
case 1: if(scrollx<-6600 && player.isTouchingGround())
{
isWorldAnimationPlaying=true;
animation=3;
}
break;
case 2: if(scrollx<-6700 && player.isTouchingGround())
{
isWorldAnimationPlaying=true;
animation=3;
}
break;
default: break;
}
if(isWorldAnimationPlaying)
{
switch(animation)
{
case 1: addObject(screen,360,200);
screen.changeType(0);
if(screen.isAppearing()==false)
{
player.setLocation(player.getX(),getHeight()-135);
setScrollx(spawnPoint);
}
if(screen.playedAnimation()==true)
{
screen.reset();
removeObject(screen);
isWorldAnimationPlaying=false;
playedAnimation=true;
}
break;
case 2: addObject(screen,360,200);
screen.changeType(1);
if(screen.isSolid()==true)
{
Greenfoot.delay(500);
screen.reset();
removeObjects(getObjects(null));
isWorldAnimationPlaying=false;
playedAnimation=false;
player.reset();
lives.updateImage(5);
setScrollx(spawnPoint);
prepare();
getLives().updateImage(5);
getHealthBar().updateImage(100);
}
break;
case 3: player.rest();
player.setInvulnerable(true);
if(player.isDoneResting())
{
addObject(screen,360,200);
screen.changeType(0);
screen.setDelay(45);
if(screen.isSolid()==true)
{
changeLevel();
if(level==-1)
return;
if(level!=-1)
screen.setDelay(1000);
}
if(screen.playedAnimation()==true)
{
screen.reset();
removeObject(screen);
isWorldAnimationPlaying=false;
playedAnimation=false;
playedSound=false;
player.setInvulnerable(false);
levelChanged=false;
}
}
break;
}
}
/*if(Greenfoot.getKey()=="F1")
{
if(debug==false)
debug=true;
else
debug=false;
player.setInvulnerable(debug);
}
if(debug==true && Greenfoot.isKeyDown("1") && level!=1)
{
changeLevel(1);
}
if(debug==true && Greenfoot.isKeyDown("2") && level!=2)
{
changeLevel(2);
}*/
}
public void changeLevel()
{
if(levelChanged)
return;
switch(level)
{
case 1: level=2;
break;
case 2: level=-1;
break;
default: break;
}
if(level==-1)
{
if(!playedSound)
{
sound[0].play();
playedSound=true;
}
player.calculateScore();
Greenfoot.delay(200);
screen.reset();
removeObject(screen);
isWorldAnimationPlaying=false;
playedAnimation=false;
playedSound=false;
player.setInvulnerable(false);
removeObjects(getObjects(null));
showScores();
return;
}
levelChanged=true;
prepare();
}
public void changeLevel(int l)
{
level=l;
prepare();
}
public void makeImages()
{
ground=null;
background=null;
ledge=null;
ground=new GreenfootImage[20];
background=new GreenfootImage[20];
ledge=new GreenfootImage[20];
switch(level)
{
case -1:
case 1: for(int i=0;i<=10;i++)
{
ground[i]=new GreenfootImage("ground_jungle"+i+".png");
background[i]=new GreenfootImage("background_jungle"+i+".png");
ledge[i]=new GreenfootImage("ledge_jungle"+i+".png");
}
break;
case 2: for(int i=0;i<=10;i++)
{
ground[i]=new GreenfootImage("ground_mountain"+i+".png");
background[i]=new GreenfootImage("background_mountain"+i+".png");
ledge[i]=new GreenfootImage("ledge_mountain"+i+".png");
}
break;
}
}
public GreenfootImage getImage(int type,int index)
{
if(index<0 || index>10)
switch(level)
{
case 1: return(new GreenfootImage("water.png"));
case 2: return(new GreenfootImage(10,10));
default: return(new GreenfootImage(10,10));
}
switch(type)
{
case 1: return(ground[index]);
case 2: return(background[index]);
case 3: return(ledge[index]);
default: return(new GreenfootImage(10,10));
}
}
public void resetScore()
{
if(UserInfo.isStorageAvailable())
{
java.util.List<UserInfo> users=UserInfo.getTop(0);
if(!users.isEmpty())
for(int i=0;i<users.size();i++)
{
users.get(i).setScore(0);
users.get(i).store();
}
}
}
public void playAnimation(int num)
{
animation=num;
isWorldAnimationPlaying=true;
}
public void setLevel(int num)
{
level=num;
}
public Player getPlayer()
{
return(player);
}
public Whip getWhip()
{
return(whip);
}
public CollisionBox getColDown()
{
return(colDown);
}
public CollisionBox getColRight()
{
return(colRight);
}
public CollisionBox getColLeft()
{
return(colLeft);
}
public CollisionBox getColPlayer()
{
return(colPlayer);
}
public HealthBar getHealthBar()
{
return(healthbar);
}
public Lives getLives()
{
return(lives);
}
public int getScrollx()
{
return(scrollx);
}
public void setScrollx(int num)
{
scrollx=num;
}
public void changeScrollx(int num)
{
scrollx=scrollx+num;
}
public int getTerrainNum()
{
return(terrainNum);
}
public void setTerrainNum(int num)
{
terrainNum=num;
}
public boolean isWorldAnimationPlaying()
{
return(isWorldAnimationPlaying);
}
public boolean playedAnimation()
{
return(playedAnimation);
}
public void resetAnimation()
{
playedAnimation=false;
}
public void removeSnakes()
{
java.util.List<Snake> list=getObjects(Snake.class);
for(int i=0;i<list.size();i++)
list.get(i).kill();
}
public boolean isDebugOn()
{
return(debug);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Scythe here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Scythe extends Trap
{
private int dir;
private int step=0;
private final int RIGHT=0;
private final int LEFT=1;
private Timer rotationTimer=new Timer();
public Scythe(int x,int del,int iniD)
{
super(x,del,iniD);
damage=50;
setImage(new GreenfootImage("scythe1.png"));
}
public void act()
{
timer.tick();
activeTimer.tick();
rotationTimer.tick();
GameWorld world=(GameWorld)getWorld();
setLocation(world.getScrollx()+360+posX,-70);
if(active==true || !activeTimer.wait(initialDelay))
activeImage();
if(active==false)
return;
if(!rotationTimer.wait(25))
{
if(dir==RIGHT)
{
if(getRotation()!=270)
turn(-5);
else
if(!timer.wait(delay))
dir=LEFT;
}else
{
if(getRotation()!=90)
turn(5);
else
if(!timer.wait(delay))
dir=RIGHT;
}
}
if(isTouchingPlayer())
getPlayer().getHurt(damage);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Trap here.
*
* @author (your name)
* @version (a version number or a date)
*/
public abstract class Trap extends Actor
{
protected int damage;
protected int delay;
protected int initialDelay;
protected int posX;
protected boolean active;
protected Timer activeTimer=new Timer();
protected Timer timer=new Timer();
public Trap(int x,int del,int iniD)
{
posX=x;
delay=del;
initialDelay=iniD;
active=false;
}
public void act()
{
}
public void activeImage()
{
active=true;
GreenfootImage image=getImage();
if(image.getTransparency()==0)
{
image.setTransparency(255);
setImage(image);
}
}
/*public boolean isTouchingGround()
{
return(getOneObjectAtOffset(0,0,Ground.class)!=null);
}*/
public Player getPlayer()
{
GameWorld world=(GameWorld)getWorld();
Player player=world.getPlayer();
return(player);
}
public CollisionBox getColPlayer()
{
GameWorld world=(GameWorld)getWorld();
CollisionBox box=world.getColPlayer();
return(box);
}
public boolean isTouchingPlayer()
{
if(!intersects(getColPlayer()))
return(false);
return(touch(getColPlayer()));
}
/*private boolean isVisuallyIntersecting(Actor actor)
{
// get width and height of images
int wA = getImage().getWidth();
int hA = getImage().getHeight();
int wB = actor.getImage().getWidth();
int hB = actor.getImage().getHeight();
// get world coordinates of origin point (0, 0) of images
int xAw = getX()-wA/2;
int yAw = getY()-hA/2;
int xBw = actor.getX()-wB/2;
int yBw = actor.getY()-hB/2;
// determine (x, y) on each image to begin checking from
// and dimensions of area to check
int xA = 0, yA = 0, xB = 0, yB = 0; // initialize start coord fields
int w = 0, h = 0; // initialize scan dimension fields
// determine values for fields just initialized
if (xAw > xBw)
{
xB = xAw-xBw;
if (xAw+wA > xBw+wB) w = wB-xB; else w = wA;
}
else
{
xA = xBw-xAw;
if (xBw+wB > xAw+wA) w = wA-xA; else w = wB;
}
if (yAw > yBw)
{
yB = yAw-yBw;
if (yAw+hA > yBw+hB) h = hB-yB; else h = hA;
}
else
{
yA = yBw-yAw;
if (yBw+hB > yAw+hA) h = hA-yA; else h = hB;
}
// perform checking
java.awt.Color trans = new java.awt.Color(0, 0, 0, 0);
for (int x=0; x<w; x++) for (int y=0; y<h; y++)
{
if (!trans.equals(getImage().getColorAt(xA+x, yA+y)) )//&&
//!trans.equals(actor.getImage().getColorAt(xB+x, yB+y)))
return true;
}
return false;
} */
/**
* This is a perfect pixel-collision method.
*
* @author (Busch2207 (Moritz L.))
* @version (09.11.2013)
* /
/** This method is a pixel perfect collision detection. Returns true, if the object touchs the given Actor */
public boolean touch(Actor a_big)
{
Actor a_small;
if(getImage().getWidth()*getImage().getHeight()>a_big.getImage().getHeight()*a_big.getImage().getWidth())
{
a_small=a_big;
a_big=this;
}
else
a_small=this;
int i_hypot=(int)Math.hypot(a_small.getImage().getWidth(),a_small.getImage().getHeight());
GreenfootImage i=new GreenfootImage(i_hypot,i_hypot);
i.drawImage(a_small.getImage(),i_hypot/2-a_small.getImage().getWidth()/2,i_hypot/2-a_small.getImage().getHeight()/2);
i.rotate(a_small.getRotation());
int w=i_hypot;
GreenfootImage Ai = a_big.getImage(),
i2=new GreenfootImage(i_hypot=(int)Math.hypot(Ai.getWidth(),Ai.getHeight()),i_hypot);
i2.drawImage(Ai,i2.getWidth()/2-Ai.getWidth()/2,i2.getHeight()/2-Ai.getHeight()/2);
i2.rotate(a_big.getRotation());
Ai=i2;
int
x_Offset=a_big.getX()-a_small.getX()-(Ai.getWidth()/2-w/2),
y_Offset=a_big.getY()-a_small.getY()-(Ai.getHeight()/2-w/2);
boolean b = true;
for(int yi =Math.max(0,y_Offset); yi<w && yi<i_hypot+y_Offset && b; yi++)
for(int xi =Math.max(0,x_Offset); xi<w && xi<i_hypot+x_Offset && b; xi++)
if(Ai.getColorAt(xi-x_Offset,yi-y_Offset).getAlpha()>0 )//&& i.getColorAt(xi,yi).getAlpha()>0)
b=false;
return !b;
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
/**
* Write a description of class CollisionBar here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class CollisionBox extends Actor
{
private int posX;
private int posY;
private int type;
private Actor actor;
public CollisionBox(Actor act,int x,int y,int width,int height)
{
/*GreenfootImage image=new GreenfootImage(width,height);
image.setColor(new Color(0,0,0,100));
image.fill();
setImage(image);*/
/*image.setColor(new Color(0,0,0,0));
image.fill();
setImage(image);*/
/*posX=x;
posY=y;*/
actor=act;
updateImage(x,y,width,height);
}
public void act()
{
if(actor.getWorld()==null)
{
getWorld().removeObject(this);
return;
}else
setLocation(actor.getX()+posX,actor.getY()+posY);
GreenfootImage image=getImage();
if(((GameWorld)getWorld()).isDebugOn())
{
image.setTransparency(255);
setImage(image);
}else
{
image.setTransparency(5);
setImage(image);
}
}
public boolean isTouchingGround()
{
if(isIntersecting(Ground.class))
return(true);
else
return(false);
}
public boolean isTouchingWall()
{
if(isIntersecting(Wall.class))
return(true);
else
return(false);
}
public boolean isTouchingWhip()
{
if(isIntersecting(Whip.class))
return(true);
else
return(false);
}
public void updateHitbox(int action,int dir)
{
switch(action)
{
case 0:
case 1:
case 2:
case 5:
case 6: updateImage(-3,0,34,90);
break;
case 3: updateImage(0,20,34,60);
break;
case 4: updateImage(0,27,34,34);
break;
case 7:
case 8: updateImage(0,27,50,34);
break;
}
if(dir==1)
posX=-posX;
}
public void updateForAction(int action,int dir)
{
switch(action)
{
case 0:
case 1:
case 2:
case 5:
case 6: updateImage(40,0,10,10);
break;
case 3: updateImage(40,20,10,10);
break;
case 4: updateImage(50,27,10,10);
break;
case 7:
case 8: updateImage(40,27,10,10);
break;
}
if(dir==1)
posX=-posX;
}
public void updateImage(int x,int y,int width,int height)
{
GreenfootImage image=new GreenfootImage(width,height);
image.setColor(new Color(225,0,255,60));
image.fill();
image.setTransparency(5);
setImage(image);
posX=x;
posY=y;
}
private boolean isIntersecting(java.lang.Class cls)
{
java.util.List actors=getIntersectingObjects(cls);
if(actors.isEmpty())
return(false);
if(isVisuallyIntersecting((Actor)actors.get(0)))
return(true);
else
if(actors.size()>1)
return(isVisuallyIntersecting((Actor)actors.get(1)));
return(false);
}
private boolean isVisuallyIntersecting(Actor actor)
{
// get width and height of images
int wA = getImage().getWidth();
int hA = getImage().getHeight();
int wB = actor.getImage().getWidth();
int hB = actor.getImage().getHeight();
// get world coordinates of origin point (0, 0) of images
int xAw = getX()-wA/2;
int yAw = getY()-hA/2;
int xBw = actor.getX()-wB/2;
int yBw = actor.getY()-hB/2;
// determine (x, y) on each image to begin checking from
// and dimensions of area to check
int xA = 0, yA = 0, xB = 0, yB = 0; // initialize start coord fields
int w = 0, h = 0; // initialize scan dimension fields
// determine values for fields just initialized
if (xAw > xBw)
{
xB = xAw-xBw;
if (xAw+wA > xBw+wB) w = wB-xB; else w = wA;
}
else
{
xA = xBw-xAw;
if (xBw+wB > xAw+wA) w = wA-xA; else w = wB;
}
if (yAw > yBw)
{
yB = yAw-yBw;
if (yAw+hA > yBw+hB) h = hB-yB; else h = hA;
}
else
{
yA = yBw-yAw;
if (yBw+hB > yAw+hA) h = hA-yA; else h = hB;
}
// perform checking
java.awt.Color trans = new java.awt.Color(0, 0, 0, 0);
for (int x=0; x<w; x++) for (int y=0; y<h; y++)
{
if (trans.equals(getImage().getColorAt(xA+x, yA+y)) || trans.equals(actor.getImage().getColorAt(xB+x, yB+y)))
return false;
}
return true;
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Boulder here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Boulder extends Trap
{
private int yVel=0;
private int dir;
private int xVel=20;
private Timer spawnTimer=new Timer();
private CollisionBox colDown;
private boolean addedToWorld=false;
private static final int RIGHT=0;
private static final int LEFT=1;
public Boulder(int x,int del,int iniD,int d,int xV,int skin)
{
super(x,del,iniD);
dir=d;
xVel=xV;
damage=10;
if(skin==9001)
damage=110;
GreenfootImage image;
switch(skin)
{
case 1: image=new GreenfootImage("rock_jungle1.png");
break;
case 2: image=new GreenfootImage("rock_jungle2.png");
break;
case 9001: image=new GreenfootImage("boulder.png");
break;
default: image=new GreenfootImage("rock.png");
break;
}
image.setTransparency(0);
setImage(image);
colDown=new CollisionBox(this,0,getImage().getHeight()/2+10,10,10);
}
public void act()
{
timer.tick();
activeTimer.tick();
GameWorld world=(GameWorld)getWorld();
if(dir==2)
{
if(getX()>getPlayer().getX())
dir=1;
else
dir=0;
}
if(addedToWorld==false)
{
addedToWorld=true;
world.addObject(colDown,getX(),getY());
}
if(active==true || !activeTimer.wait(initialDelay))
activeImage();
if(active==false)
return;
if(colDown.isTouchingGround())
{
yVel=-1;
setLocation(getX(),world.getHeight()-95-getImage().getHeight()/2);
}
yVel+=1;
setLocation(world.getScrollx()+360+posX,getY()+yVel);
if(isTouchingPlayer())
getPlayer().getHurt(damage);
if(timer.wait(100))
return;
if(dir==RIGHT)
{
posX+=xVel;
turn(45);
}
else
{
posX-=xVel;
turn(-45);
}
if(getY()>world.getHeight()+getImage().getHeight())
world.removeObject(this);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
/**
* Write a description of class Screen here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Screen extends Actor
{
private boolean isAnimationPlaying;
private boolean isAppearing;
private boolean playedAnimation;
private boolean isSolid;
private int type;
private boolean newImage;
private int delay;
private Timer timer=new Timer();
public Screen()
{
isAnimationPlaying=false;
playedAnimation=false;
isAppearing=true;
isSolid=false;
newImage=true;
type=0;
delay=0;
GreenfootImage image=new GreenfootImage(720,480);
image.setColor(Color.black);
image.fill();
image.setTransparency(0);
setImage(image);
}
public void reset()
{
isAnimationPlaying=false;
playedAnimation=false;
isAppearing=true;
isSolid=false;
newImage=true;
type=0;
delay=0;
GreenfootImage image=new GreenfootImage(720,480);
image.setColor(Color.black);
image.fill();
image.setTransparency(0);
setImage(image);
}
public void act()
{
timer.tick();
if(timer.wait(delay))
return;
if(isAppearing)
appear();
else
disappear();
}
public void show()
{
GreenfootImage image=getImage();
image.setTransparency(0);
setImage(image);
}
public void disappear()
{
isSolid=false;
GreenfootImage image=getImage();
if(image.getTransparency()<5)
{
playedAnimation=true;
GameWorld world=(GameWorld)getWorld();
return;
}
image.setTransparency(image.getTransparency()-5);
setImage(image);
}
public void appear()
{
isAppearing=true;
GreenfootImage image=getImage();
if(newImage==true)
{
image.setTransparency(0);
newImage=false;
}
if(image.getTransparency()>250)
{
isAppearing=false;
isSolid=true;
return;
}
image.setTransparency(image.getTransparency()+5);
setImage(image);
}
public boolean isAppearing()
{
return(isAppearing);
}
public boolean playedAnimation()
{
return(playedAnimation);
}
public boolean isSolid()
{
return(isSolid);
}
public void changeType(int num)
{
if(type!=num)
{
switch(num)
{
case 0: GreenfootImage image=new GreenfootImage(720,480);
image.setColor(Color.black);
image.fill();
image.setTransparency(0);
setImage(image);
break;
case 1: setImage("you_lose.png");
break;
}
type=num;
newImage=true;
}
}
public void setDelay(int del)
{
delay=del;
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Button here.
*
* @author (your name)
* @version (a version number or a date)
*/
public abstract class Button extends Actor
{
protected int xPos;
protected int yPos;
public Button(int x,int y)
{
xPos=x;
yPos=y;
}
public void act()
{
if(isMouseOver())
setLocation(xPos,yPos-5);
else
setLocation(xPos,yPos);
}
public boolean isMouseOver()
{
MouseInfo mouse=getMouse();
if(mouse==null)
return(false);
int xIni,yIni,xFin,yFin;
xIni=xPos-getImage().getWidth()/2;
xFin=xPos+getImage().getWidth()/2;
yIni=yPos-getImage().getHeight()/2;
yFin=yPos+getImage().getHeight()/2;
if(mouse.getX()>xIni && mouse.getX()<xFin && mouse.getY()>yIni && mouse.getY()<yFin)
return(true);
else
return(false);
}
public boolean clicked()
{
if(getMouse().getButton()==1 && getMouse().getClickCount()==1)
return(true);
else
return(false);
}
public MouseInfo getMouse()
{
return(Greenfoot.getMouseInfo());
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
/**
* Write a description of class CollisionBar here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class CollisionBar extends Actor
{
private int posX;
private int posY;
private int type;
private final int HORIZONTAL=0;
private final int VERTICAL=1;
public CollisionBar(int x,int y,int t)
{
GreenfootImage image=new GreenfootImage(10,10);
/*image.setColor(Color.BLACK);
image.fill();
setImage(image);*/
image.setColor(new Color(0,0,0,0));
image.fill();
setImage(image);
posX=x;
posY=y;
type=t;
}
public void act()
{
GameWorld world=(GameWorld)getWorld();
Player player=world.getPlayer();
if(type==HORIZONTAL)
{
setLocation(posX,player.getY()+posY);
}else
setLocation(player.getX()+posX,posY);
}
public boolean isTouchingGround()
{
if(isIntersecting(Ground.class))
return(true);
else
return(false);
}
private boolean isIntersecting(java.lang.Class cls)
{
java.util.List actors=getIntersectingObjects(Ground.class);
if(actors.isEmpty())
return(false);
if(isVisuallyIntersecting((Actor)actors.get(0)))
return(true);
else
if(actors.size()>1)
return(isVisuallyIntersecting((Actor)actors.get(1)));
return(false);
}
private boolean isVisuallyIntersecting(Actor actor)
{
// get width and height of images
int wA = getImage().getWidth();
int hA = getImage().getHeight();
int wB = actor.getImage().getWidth();
int hB = actor.getImage().getHeight();
// get world coordinates of origin point (0, 0) of images
int xAw = getX()-wA/2;
int yAw = getY()-hA/2;
int xBw = actor.getX()-wB/2;
int yBw = actor.getY()-hB/2;
// determine (x, y) on each image to begin checking from
// and dimensions of area to check
int xA = 0, yA = 0, xB = 0, yB = 0; // initialize start coord fields
int w = 0, h = 0; // initialize scan dimension fields
// determine values for fields just initialized
if (xAw > xBw)
{
xB = xAw-xBw;
if (xAw+wA > xBw+wB) w = wB-xB; else w = wA;
}
else
{
xA = xBw-xAw;
if (xBw+wB > xAw+wA) w = wA-xA; else w = wB;
}
if (yAw > yBw)
{
yB = yAw-yBw;
if (yAw+hA > yBw+hB) h = hB-yB; else h = hA;
}
else
{
yA = yBw-yAw;
if (yBw+hB > yAw+hA) h = hA-yA; else h = hB;
}
// perform checking
java.awt.Color trans = new java.awt.Color(0, 0, 0, 0);
for (int x=0; x<w; x++) for (int y=0; y<h; y++)
{
if (/*trans.equals(getImage().getColorAt(xA+x, yA+y)) || */trans.equals(actor.getImage().getColorAt(xB+x, yB+y)))
return false;
}
return true;
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
import java.util.List;
/**
* An actor class that can display a scoreboard, using Greenfoot's
* UserInfo class.
*
* You typically use this by including some code into the world for when your game ends:
*
* <pre>
* addObject(new ScoreBoard(800, 600), getWidth() / 2, getHeight() / 2);
* </pre>
*
* Where 800 by 600 should be replaced by the desired size of the score board.
*
* @author Neil Brown
* @version 1.0
*/
public class ScoreBoard extends Actor
{
/**
* Constructor for objects of class ScoreBoard.
* <p>
* You can specify the width and height that the score board should be, but
* a minimum width of 600 will be enforced.
*/
public ScoreBoard(int width, int height)
{
setImage(new GreenfootImage(width, height));
drawScores();
}
private void drawScores()
{
getImage().setColor(new Color(0,0,0,0));
getImage().fill();
drawPanel(UserInfo.getTop(5));
drawUserPanel();
}
private void drawPanel(List users)
{
if (users == null)
return;
for (int i=0,y=77;i<users.size();i++,y+=59)
{
UserInfo playerData = (UserInfo)users.get(i);
int score=playerData.getScore()*-1;
int minutes=score/60;
int seconds=score%60;
getImage().drawImage(playerData.getUserImage(), 63, y);
drawMessage(minutes+"' "+seconds+"''", 160, y-5,20);
drawMessage(playerData.getUserName(), 160, y+20,20);
}
}
private void drawUserPanel()
{
if(UserInfo.isStorageAvailable())
{
UserInfo myInfo=UserInfo.getMyInfo();
if(myInfo!=null)
{
int score=myInfo.getScore()*-1;
int rank=myInfo.getRank();
int minutes=score/60;
int seconds=score%60;
if(score!=0)
drawMessage(minutes+"' "+seconds+"''", 480, 245,30);
else
drawMessage("-", 480, 245,30);
getImage().drawImage(myInfo.getUserImage(), 445, 177);
if(rank!=-1)
drawMessage(rank+"", 550, 180,40);
else
drawMessage("-", 550, 182,40);
}
}
}
public void drawMessage(String message,int x,int y,int fontSize)
{
GreenfootImage image=new GreenfootImage(message.length()*fontSize/2,fontSize+10);
image.clear();
image.setColor(new Color(0,0,0,0));
image.fill();
image.setColor(new Color(255,255,255));
image.setFont(new java.awt.Font("Impact",java.awt.Font.PLAIN,fontSize));
image.drawString(message,0,image.getHeight()/2+10);
getImage().drawImage(image,x,y);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Play here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Play extends Button
{
public Play(int x,int y)
{
super(x,y);
setImage(new GreenfootImage("play0.png"));
}
public void act()
{
super.act();
if(isMouseOver())
{
setImage(new GreenfootImage("play1.png"));
if(clicked())
((GameWorld)getWorld()).play();
}
else
setImage(new GreenfootImage("play0.png"));
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Spikes here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Spikes extends Trap
{
private int skinIndex;
public Spikes(int x,int del,int iniD)
{
super(x,del,iniD);
damage=10;
skinIndex=0;
GreenfootImage image=new GreenfootImage("spikes0.png");
image.setTransparency(0);
setImage(image);
}
public void act()
{
timer.tick();
activeTimer.tick();
if(active==true || !activeTimer.wait(initialDelay))
activeImage();
if(active==false)
return;
GameWorld world=(GameWorld)getWorld();
if(skinIndex!=6)
setLocation(world.getScrollx()+360+posX,world.getHeight()-80-getImage().getHeight()/2);
else
setLocation(world.getScrollx()+360+posX,world.getHeight());
if(skinIndex<6)
{
if(!timer.wait(50))
{
skinIndex++;
switch(skinIndex)
{
case 0: setImage(new GreenfootImage("spikes0.png"));
break;
case 1: setImage(new GreenfootImage("spikes1.png"));
break;
case 2: setImage(new GreenfootImage("spikes2.png"));
break;
case 3: setImage(new GreenfootImage("spikes3.png"));
break;
case 4: setImage(new GreenfootImage("spikes2.png"));
break;
case 5: setImage(new GreenfootImage("spikes1.png"));
break;
default: setImage(new GreenfootImage(10,10));
break;
}
}
}
else
if(!timer.wait(delay))
skinIndex=0;
if(isTouchingPlayer() && skinIndex!=0)
((GameWorld)getWorld()).getPlayer().getHurt(10);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Player here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Player extends Actor
{
private Whip whip;
private CollisionBox colDown;
private CollisionBox colPlayer;
private CollisionBox colRight;
private CollisionBox colLeft;
private GameWorld world;
private int runIndex;
private int rollIndex;
private int whipIndex;
private int restIndex;
private int dizzyIndex;
private int dizzyRepeat;
private int animationDelay;
private int dir;
private int action;
private int lastAction;
private int yVel;
private Timer timer=new Timer();
private Timer rollTimer=new Timer();
private Timer whipTimer=new Timer();
private Timer scoreTimer=new Timer();
private GreenfootImage[][][] skins;
private boolean isJumping;
private boolean isRolling;
private boolean isDizzy;
private boolean isGettingUp;
private boolean isFlying;
private boolean playingAnimation;
private boolean manMode=false;
private int health;
private boolean invulnerable;
private int lives;
private int score;
private static final int RIGHT=0;
private static final int LEFT=1;
private static final int UP=2;
private static final int DOWN=3;
public Player()
{
health=100;
lives=5;
invulnerable=false;
whipTimer.setTime(9001);
runIndex=0;
rollIndex=0;
whipIndex=0;
restIndex=0;
dizzyIndex=0;
dizzyRepeat=0;
animationDelay=15;
dir=RIGHT;
isJumping=false;
isRolling=false;
isDizzy=false;
isGettingUp=false;
isFlying=false;
playingAnimation=false;
action=0;
lastAction=0;
yVel=-1;
skins=new GreenfootImage[11][11][2];
createImageList();
}
public void act()
{
timer.tick();
rollTimer.tick();
whipTimer.tick();
scoreTimer.tick();
world=(GameWorld)getWorld();
debug();
if(world.isWorldAnimationPlaying())
return;
whip=world.getWhip();
colDown=world.getColDown();
colPlayer=world.getColPlayer();
colRight=world.getColRight();
colLeft=world.getColLeft();
if(isTouchingGround())
{
if(action!=7)
yVel= -1;
setLocation(getX(),getWorld().getHeight()-145);
isJumping=false;
if(!isAnyKeyDown() && action<5)
action=0;
if((Greenfoot.isKeyDown("right") || Greenfoot.isKeyDown("left")) && action<5 && canMove())
action=1;
if(Greenfoot.isKeyDown("down") && action<5)
action=3;
if(Greenfoot.isKeyDown("s") && action<5 && isDizzy==false)
action=4;
if(Greenfoot.isKeyDown("up") && action<5)
yVel=-14;
if(Greenfoot.isKeyDown("a") && action<6 && whipTimer.getTime()>1000)
action=5;
}else
{
if(Greenfoot.isKeyDown("a") && action<7 && whipTimer.getTime()>1000)
action=6;
else
if(action<4)
action=2;
}
if(getY()>world.getHeight())
action=8;
if(action==2 && isWallAbove()==true)
yVel=1;
if(action!=lastAction)
aftermath();
else
switch(action)
{
case 0: stand();
break;
case 1: run();
break;
case 2: jump();
break;
case 3: crouch();
break;
case 4: roll();
break;
case 5: whip();
break;
case 6: whipJump();
break;
case 7: fall();
break;
case 8: die();
break;
default: break;
}
yVel=yVel+1;
setLocation(getX(),getY()+yVel);
if(getY()>world.getHeight()+100)
{
//setLocation(getX(),100);
action=8;
}
colPlayer.updateHitbox(action,dir);
colRight.updateForAction(action,RIGHT);
colLeft.updateForAction(action,LEFT);
}
public void createImageList()
{
skins[0][0][0]=new GreenfootImage("standing0.png");
skins[0][0][1]=new GreenfootImage("standing0.png");
skins[0][0][1].mirrorHorizontally();
for(int i=0;i<=8;i++)
{
skins[1][i][0]=new GreenfootImage("running"+i+".png");
skins[1][i][1]=new GreenfootImage("running"+i+".png");
skins[1][i][1].mirrorHorizontally();
}
skins[2][0][0]=new GreenfootImage("jumping0.png");
skins[2][0][1]=new GreenfootImage("jumping0.png");
skins[2][0][1].mirrorHorizontally();
skins[2][1][0]=new GreenfootImage("jumping1.png");
skins[2][1][1]=new GreenfootImage("jumping1.png");
skins[2][1][1].mirrorHorizontally();
skins[3][0][0]=new GreenfootImage("crouching0.png");
skins[3][0][1]=new GreenfootImage("crouching0.png");
skins[3][0][1].mirrorHorizontally();
for(int i=0;i<=6;i++)
{
skins[4][i][0]=new GreenfootImage("rolling"+i+".png");
skins[4][i][1]=new GreenfootImage("rolling"+i+".png");
skins[4][i][1].mirrorHorizontally();
}
for(int i=0;i<=4;i++)
{
skins[5][i][0]=new GreenfootImage("whip"+i+".png");
skins[5][i][1]=new GreenfootImage("whip"+i+".png");
skins[5][i][1].mirrorHorizontally();
}
for(int i=0;i<=3;i++)
{
skins[6][i][0]=new GreenfootImage("whipJump"+i+".png");
skins[6][i][1]=new GreenfootImage("whipJump"+i+".png");
skins[6][i][1].mirrorHorizontally();
}
skins[7][0][0]=new GreenfootImage("falling0.png");
skins[7][0][1]=new GreenfootImage("falling0.png");
skins[7][0][1].mirrorHorizontally();
skins[8][0][0]=new GreenfootImage("dead0.png");
skins[8][0][1]=new GreenfootImage("dead0.png");
skins[8][0][1].mirrorHorizontally();
for(int i=0;i<=2;i++)
{
skins[9][i][0]=new GreenfootImage("dizzy"+i+".png");
skins[9][i][1]=new GreenfootImage("dizzy"+i+".png");
skins[9][i][1].mirrorHorizontally();
}
for(int i=0;i<=10;i++)
skins[10][i][0]=new GreenfootImage("resting"+i+".png");
}
public void stand()
{
action=0;
if(lastAction!=action)
return;
setSkin(skins[0][0][dir]);
}
public void run()
{
action=1;
if(lastAction!=action)
return;
if(Greenfoot.isKeyDown("right"))
{
dir=RIGHT;
}
else
if(Greenfoot.isKeyDown("left"))
{
dir=LEFT;
}
if(timer.wait(animationDelay))
return;
scroll(17);
if(runIndex>8)
runIndex=0;
setSkin(skins[1][runIndex][dir]);
runIndex++;
}
public void jump()
{
action=2;
if(lastAction!=action)
return;
if(Greenfoot.isKeyDown("right"))
{
dir=RIGHT;
scroll(10);
}
else
if(Greenfoot.isKeyDown("left"))
{
dir=LEFT;
scroll(10);
}
if(isJumping==false)
{
setSkin(skins[2][0][dir]);
if(timer.wait(200))
return;
isJumping=true;
}else
setSkin(skins[2][1][dir]);
}
public void crouch()
{
action=3;
if(lastAction!=action)
return;
if(Greenfoot.isKeyDown("right"))
dir=RIGHT;
else
if(Greenfoot.isKeyDown("left"))
dir=LEFT;
setSkin(skins[3][0][dir]);
}
public void roll()
{
action=4;
rollTimer.count();
if(lastAction!=action)
return;
if(timer.wait(40) && isRolling==false)
return;
if(timer.wait(animationDelay) && isRolling==true)
return;
if(isRolling==false && rollIndex<2)
{
setSkin(skins[4][rollIndex][dir]);
rollIndex++;
scroll(25);
return;
}
isRolling=true;
setSkin(skins[4][rollIndex][dir]);
scroll(17);
rollIndex++;
if(rollIndex>5)
rollIndex=2;
}
public void whip()
{
action=5;
if(lastAction!=action)
return;
whipTimer.reset();
if(timer.wait(40))
return;
if(whipIndex>4)
{
action=0;
/*if(whip.isTouchingLedge())
{
setSkin(skins[6][3][dir]);
yVel=-20;
scroll(100);
isFlying=true;
}*/
GreenfootSound sound=new GreenfootSound("whip_crack.mp3");
sound.play();
return;
}
setSkin(skins[5][whipIndex][dir]);
whip.setSkin(whipIndex,dir);
whipIndex++;
}
public void whipJump()
{
action=6;
if(lastAction!=action)
return;
whipTimer.reset();
if(whipIndex<=2)
{
setSkin(skins[6][whipIndex][dir]);
whip.setSkin(whipIndex+5,dir);
}else
whip.attach(7,dir);
if(Greenfoot.isKeyDown("right"))
{
dir=RIGHT;
scroll(10);
}
else
if(Greenfoot.isKeyDown("left"))
{
dir=LEFT;
scroll(10);
}
if(timer.wait(40))
return;
if(whipIndex>2)
{
action=2;
if(whip.isTouchingLedge())
{
setSkin(skins[6][3][dir]);
yVel=-17;
scroll(100);
isFlying=true;
}
GreenfootSound sound=new GreenfootSound("whip_hit.mp3");
sound.play();
return;
}
whipIndex++;
}
public int getHealth()
{
return(health);
}
public void getHurt(int damage)
{
if(invulnerable==true)
return;
action=7;
if(invulnerable==false)
{
invulnerable=true;
if(health>damage)
health-=damage;
else
if(health>10)
health=10;
else
health=0;
world.getHealthBar().updateImage(health);
yVel=-10;
setLocation(getX(),getY()+yVel);
}
}
public void fall()
{
setImage(skins[7][0][dir]);
scroll(-10);
whip.hide();
if(isTouchingGround())
{
invulnerable=false;
//yVel=-5;
if(health>0)
action=0;
else
{
action=8;
invulnerable=true;
}
}
}
public void die()
{
action=8;
invulnerable=true;
setSkin(skins[8][0][dir]);
whip.hide();
if(world.playedAnimation()==false)
{
lives--;
health=0;
world.getHealthBar().updateImage(health);
world.getLives().updateImage(lives);
world.playAnimation(1);
playingAnimation=true;
if(lives==0)
world.playAnimation(2);
world.removeSnakes();
return;
}
health=100;
world.getHealthBar().updateImage(health);
setSkin(skins[9][dizzyIndex][dir]);
if(dizzyRepeat<5)
{
if(timer.wait(100))
return;
dizzyIndex++;
dizzyRepeat++;
if(dizzyIndex>1)
dizzyIndex=0;
return;
}
setSkin(skins[9][2][dir]);
if(timer.wait(120))
return;
rollTimer.reset();
isDizzy=false;
resetIndex();
action=0;
invulnerable=false;
isGettingUp=false;
playingAnimation=false;
world.resetAnimation();
}
public void aftermath()
{
if(!(action<8))
{
lastAction=action;
rollTimer.reset();
resetIndex();
return;
}
switch(lastAction)
{
case 4: if(rollTimer.getTime()<1000)
{
setSkin(skins[4][6][dir]);
if(timer.wait(60))
return;
scroll(17);
lastAction=action;
resetIndex();
}else
{
isDizzy=true;
setSkin(skins[9][dizzyIndex][dir]);
if(dizzyRepeat<3)
{
if(timer.wait(100))
return;
dizzyIndex++;
dizzyRepeat++;
if(dizzyIndex>1)
dizzyIndex=0;
return;
}
setSkin(skins[9][2][dir]);
if(timer.wait(120))
return;
lastAction=action;
resetIndex();
}
rollTimer.reset();
isDizzy=false;
break;
case 5: case 6: whip.hide();
if(isFlying==true)
{
if((Greenfoot.isKeyDown("right") && dir==RIGHT) || (Greenfoot.isKeyDown("left") && dir==LEFT))
scroll(10);
if(timer.wait(200))
return;
whipTimer.reset();
//whipTimer.setCount(9001);
whipTimer.setTime(950);
}else
whipTimer.count();
isFlying=false;
lastAction=action;
resetIndex();
break;
default: lastAction=action;
timer.reset();
resetIndex();
break;
}
}
public void resetIndex()
{
if(action!=4)
{
rollIndex=0;
dizzyIndex=0;
dizzyRepeat=0;
isRolling=false;
}
if(action!=1)
runIndex=0;
if(action!=5)
whipIndex=0;
}
public void scroll(int num)
{
if(!canMove())
return;
switch(dir)
{
case RIGHT: world.changeScrollx(num*-1);
break;
case LEFT: world.changeScrollx(num);
break;
default: break;
}
}
public void setSkin(GreenfootImage skin)
{
setImage(skin);
}
public boolean isTouchingGround()
{
if(colDown.isTouchingGround() && yVel>-1)
return(true);
else
return(false);
}
public boolean canMove()
{
/*int distance=getImage().getWidth()/2+10;
if(Greenfoot.isKeyDown("right"))//dir==RIGHT)
if(getOneObjectAtOffset(50,0,Ground.class)==null &&
(getOneObjectAtOffset(distance,0,Wall.class)==null && action!=5) ||
(getOneObjectAtOffset(distance,25,Wall.class)==null && action==5))
return(true);
else
return(false);
else
if(Greenfoot.isKeyDown("left"))
if(getOneObjectAtOffset(-50,0,Ground.class)==null &&
(getOneObjectAtOffset(-distance,0,Wall.class)==null && action!=5) ||
(getOneObjectAtOffset(-distance,25,Wall.class)==null && action==5))
return(true);
else
return(false);
return(true);*/
if(Greenfoot.isKeyDown("right"))
{
if(!colRight.isTouchingGround() && !colRight.isTouchingWall())
return(true);
else
return(false);
}
else
if(Greenfoot.isKeyDown("left"))
{
if(!colLeft.isTouchingGround() && !colLeft.isTouchingWall())
return(true);
else
return(false);
}else
if(dir==RIGHT)
{
if(!colRight.isTouchingGround() && !colRight.isTouchingWall())
return(true);
else
return(false);
}
else
if(dir==LEFT)
{
if(!colLeft.isTouchingGround() && !colLeft.isTouchingWall())
return(true);
else
return(false);
}
return(true);
}
public boolean isInvulnerable()
{
return(invulnerable);
}
public void setInvulnerable(boolean state)
{
invulnerable=state;
}
public boolean isWallAbove()
{
if(getOneObjectAtOffset(0,-getImage().getHeight()/2-5,Wall.class)!=null)
return(true);
else
return(false);
}
public void setPlayingAnimation(boolean state)
{
playingAnimation=state;
}
/* private boolean isIntersecting(java.lang.Class cls)
{
Actor actor=getOneIntersectingObject(cls);
if(actor==null)
return(false);
return(isVisuallyIntersecting(actor));
java.util.List actors=getIntersectingObjects(Ground.class);
if(actors.isEmpty())
return(false);
if(isVisuallyIntersecting((Actor)actors.get(0)))
return(true);
else
if(actors.size()>1)
return(isVisuallyIntersecting((Actor)actors.get(1)));
return(false);
}
private boolean isVisuallyIntersecting(Actor actor)
{
// get width and height of images
int wA = getImage().getWidth();
int hA = getImage().getHeight();
int wB = actor.getImage().getWidth();
int hB = actor.getImage().getHeight();
// get world coordinates of origin point (0, 0) of images
int xAw = getX()-wA/2;
int yAw = getY()-hA/2;
int xBw = actor.getX()-wB/2;
int yBw = actor.getY()-hB/2;
// determine (x, y) on each image to begin checking from
// and dimensions of area to check
int xA = 0, yA = 0, xB = 0, yB = 0; // initialize start coord fields
int w = 0, h = 0; // initialize scan dimension fields
// determine values for fields just initialized
if (xAw > xBw)
{
xB = xAw-xBw;
if (xAw+wA > xBw+wB) w = wB-xB; else w = wA;
}
else
{
xA = xBw-xAw;
if (xBw+wB > xAw+wA) w = wA-xA; else w = wB;
}
if (yAw > yBw)
{
yB = yAw-yBw;
if (yAw+hA > yBw+hB) h = hB-yB; else h = hA;
}
else
{
yA = yBw-yAw;
if (yBw+hB > yAw+hA) h = hA-yA; else h = hB;
}
// perform checking
java.awt.Color trans = new java.awt.Color(0, 0, 0, 0);
for (int x=0; x<w; x++) for (int y=0; y<h; y++)
{
if (!trans.equals(getImage().getColorAt(xA+x, yA+y)) &&
!trans.equals(actor.getImage().getColorAt(xB+x, yB+y)))
return true;
}
return false;
}
public boolean isAnyKeyDown()
{
String keys = "abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_-+={[}]|\\<,>.?/`~";
String[] specialKeys = { "enter", "escape", "space", "backspace", "tab", "shift", "control", "up", "down", "left", "right", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12" };
int i = 0;
for (i=0; i<keys.length(); i++)
if (Greenfoot.isKeyDown(keys.substring(i, i+1)))
break;
boolean keyFoundDown = i < keys.length();
if (!keyFoundDown)
{
for (i=0; i<specialKeys.length; i++)
if (Greenfoot.isKeyDown(specialKeys[i]))
break;
keyFoundDown = i < specialKeys.length;
}
return(keyFoundDown);
} */
public boolean isAnyKeyDown()
{
String[] keys={"right","left","up","down","a","s"};
int i=0;
for(i=0;i<keys.length;i++)
if(Greenfoot.isKeyDown(keys[i]))
break;
return(i<keys.length);
}
public void rest()
{
int index=0;
if(timer.wait(100))
return;
restIndex++;
switch(restIndex)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10: index=restIndex;
break;
case 11: index=4;
break;
case 12: index=3;
break;
default: index=2;
break;
}
setSkin(skins[10][index][0]);
}
public boolean isDoneResting()
{
if(restIndex>14)
return(true);
else
return(false);
}
public void reset()
{
health=100;
lives=5;
invulnerable=false;
whipTimer.setTime(9001);
runIndex=0;
rollIndex=0;
whipIndex=0;
restIndex=0;
dizzyIndex=0;
dizzyRepeat=0;
animationDelay=15;
dir=RIGHT;
isJumping=false;
isRolling=false;
isDizzy=false;
isGettingUp=false;
isFlying=false;
playingAnimation=false;
action=0;
lastAction=0;
yVel=-1;
}
public void debug()
{
world.removeObjects(world.getObjects(Display.class));
if(world.isDebugOn())
{
world.addObject(new Display(health+""),450,100);
world.addObject(new Display("Health",20),450,70);/*
world.addObject(new Display(action+""),100,100);
world.addObject(new Display("Action",20),110,70);
world.addObject(new Display(lastAction+""),170,100);
world.addObject(new Display("Last Action",20),190,70);
world.addObject(new Display(whipTimer.getCount()+"",20),200,120);
world.addObject(new Display("A: Latigo S: Rodar",20),400,70);
world.addObject(new Display("yVel",20),680,140);
world.addObject(new Display(yVel+"",20),680,170);*/
world.addObject(new Display(action+""),300,100);
world.addObject(new Display("Action",20),310,70);
world.addObject(new Display("scroll",20),680,70);
world.addObject(new Display(world.getScrollx()*-1+"",20),680,100);
world.addObject(new Display("Invulnerable",20),680,150);
if(invulnerable==true)
world.addObject(new Display("True",20),680,170);
else
world.addObject(new Display("False",20),680,175);
}
}
public void calculateScore()
{
int newScore=(scoreTimer.getTime()/1000)*-1;
if (UserInfo.isStorageAvailable())
{
UserInfo myInfo = UserInfo.getMyInfo();
if (newScore > myInfo.getScore() || myInfo.getScore()==0)
{
myInfo.setScore(newScore);
myInfo.store(); // write back to server
}
}
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class GUI here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class GUI extends Actor
{
public GUI()
{
setImage("gui.png");
}
public void act()
{
// Add your action code here.
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Whip here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Whip extends Actor
{
private GreenfootImage[][] skins=new GreenfootImage[20][2];
private Player player;
public Whip(Player character)
{
player=character;
loadImages();
setImage(new GreenfootImage(10,10));
}
public void loadImages()
{
for(int i=0;i<=7;i++)
{
skins[i][0]=new GreenfootImage("whipW"+i+".png");
skins[i][1]=new GreenfootImage("whipW"+i+".png");
skins[i][1].mirrorHorizontally();
}
}
public void setSkin(int whipIndex,int dir)
{
setImage(skins[whipIndex][dir]);
attach(whipIndex,dir);
}
public void hide()
{
GreenfootImage image=new GreenfootImage(10,10);
image.clear();
setImage(image);
setLocation(360,400);
}
public void attach(int whipIndex,int dir)
{
int x=player.getX();
int y=player.getY();
int direction;
if(dir==0)
direction=1;
else
direction=-1;
switch(whipIndex)
{
case 0: setLocation(x+direction*(-60),y+(36));
break;
case 1: setLocation(x+direction*(-80),y+(20));
break;
case 2: setLocation(x+direction*(-57),y+(0));
break;
case 3: setLocation(x+direction*(65),y+(-30));
break;
case 4: setLocation(x+direction*(102),y+(15));
break;
case 5: setLocation(x+direction*(-53),y+(35));
break;
case 6: setLocation(x+direction*(-64),y+(-44));
break;
case 7: setLocation(x+direction*(80),y+(-123));
break;
default: break;
}
}
public void act()
{
// Add your action code here.
}
public boolean isTouchingLedge()
{
java.util.List<Ledge> ledge=getIntersectingObjects(Ledge.class);
//Ledge ledge=(Ledge)getOneIntersectingObject(Ledge.class);
if(ledge==null)
return(false);
//return(isVisuallyIntersecting(ledge));
for(int i=0;i<ledge.size();i++)
{
if(isVisuallyIntersecting(ledge.get(i)))
return(true);
}
return(false);
//return(true);
}
private boolean isVisuallyIntersecting(Actor actor)
{
// get width and height of images
int wA = getImage().getWidth();
int hA = getImage().getHeight();
int wB = actor.getImage().getWidth();
int hB = actor.getImage().getHeight();
// get world coordinates of origin point (0, 0) of images
int xAw = getX()-wA/2;
int yAw = getY()-hA/2;
int xBw = actor.getX()-wB/2;
int yBw = actor.getY()-hB/2;
// determine (x, y) on each image to begin checking from
// and dimensions of area to check
int xA = 0, yA = 0, xB = 0, yB = 0; // initialize start coord fields
int w = 0, h = 0; // initialize scan dimension fields
// determine values for fields just initialized
if (xAw > xBw)
{
xB = xAw-xBw;
if (xAw+wA > xBw+wB) w = wB-xB; else w = wA;
}
else
{
xA = xBw-xAw;
if (xBw+wB > xAw+wA) w = wA-xA; else w = wB;
}
if (yAw > yBw)
{
yB = yAw-yBw;
if (yAw+hA > yBw+hB) h = hB-yB; else h = hA;
}
else
{
yA = yBw-yAw;
if (yBw+hB > yAw+hA) h = hA-yA; else h = hB;
}
// perform checking
java.awt.Color trans = new java.awt.Color(0, 0, 0, 0);
for (int x=0; x<w; x++) for (int y=0; y<h; y++)
{
if (!trans.equals(getImage().getColorAt(xA+x, yA+y)) &&
!trans.equals(actor.getImage().getColorAt(xB+x, yB+y)))
return true;
}
return false;
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Return here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Return extends Button
{
public Return(int x,int y)
{
super(x,y);
setImage(new GreenfootImage("return0.png"));
}
public void act()
{
super.act();
if(isMouseOver())
{
setImage(new GreenfootImage("return1.png"));
if(clicked())
((GameWorld)getWorld()).mainMenu();
}
else
setImage(new GreenfootImage("return0.png"));
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Ledge here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Ledge extends Actor
{
int index;
int terrainNum;
/**
* Creates a new Ground which the player can stand on. Receives the index.
*/
public Ledge(int num)
{
index=num;
terrainNum=1;
//loadImages();
//setSkin();
}
/* public void loadImages()
{
for(int i=0;i<=10;i++)
{
images[i]=new GreenfootImage("ledge_jungle"+i+".png");
}
}*/
public void act()
{
setSkin();
GameWorld world=(GameWorld)getWorld();
int scrollx=world.getScrollx();
int width=world.getWidth();
int num=world.getTerrainNum();
setLocation(scrollx+width*index,world.getHeight()/2);
if(terrainNum<num)
{
index--;
terrainNum=num;
}else
if(terrainNum>num)
{
index++;
terrainNum=num;
}
}
public void setSkin()
{
setImage(((GameWorld)getWorld()).getImage(3,index));
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class BoulderSpawner here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class BoulderSpawner extends Trap
{
private int dir=0;
private int skin=0;
private int xVel=20;
public BoulderSpawner(int x,int del,int iniD,int d,int xV,int sk)
{
super(x,del,iniD);
setImage(new GreenfootImage(10,10));
dir=d;
skin=sk;
xVel=xV;
}
public void act()
{
timer.tick();
activeTimer.tick();
if(active==true || !activeTimer.wait(initialDelay))
activeImage();
if(active==false)
return;
if(timer.wait(delay))
return;
GameWorld world=(GameWorld)getWorld();
world.addObject(new Boulder(posX,0,0,dir,xVel,skin),world.getScrollx()+360+posX,0);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Wall here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Wall extends Trap
{
private boolean goingDown;
private int minY;
private int maxY;
public Wall(int x,int del,int iniD,int min,int max,int type)
{
super(x,del,iniD);
goingDown=true;
minY=min;
maxY=max;
damage=30;
switch(type)
{
case 1: setImage(new GreenfootImage("wall_jungle.png"));
break;
default: setImage(new GreenfootImage("wall.png"));
break;
}
GreenfootImage image=getImage();
image.setTransparency(0);
setImage(image);
}
public void act()
{
timer.tick();
activeTimer.tick();
GameWorld world=(GameWorld)getWorld();
setLocation(world.getScrollx()+360+posX,getY());
if(active==true || !activeTimer.wait(initialDelay))
activeImage();
if(active==false)
return;
if(goingDown==true)
{
if(getY()+getImage().getHeight()/2>maxY)
{
if(!timer.wait(delay))
goingDown=false;
}else
setLocation(getX(),getY()+1);
}
else
{
if(getY()+getImage().getHeight()/2<minY)
{
if(!timer.wait(delay))
goingDown=true;
}else
setLocation(getX(),getY()-1);
}
Player player=getPlayer();
if(goingDown && isTouchingPlayer())
player.getHurt(damage);
}
public boolean isPlayerDown()
{
for(int i=2;i<getImage().getWidth()-2;i++)
if(getOneObjectAtOffset(i,getImage().getHeight()/2,Player.class)!=null && isTouchingPlayer())
return(true);
return(false);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class SnakeSpawner here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class SnakeSpawner extends Trap
{
public SnakeSpawner(int x,int del,int iniD)
{
super(x,del,iniD);
setImage(new GreenfootImage(10,10));
}
public void act()
{
timer.tick();
activeTimer.tick();
if(active==true || !activeTimer.wait(initialDelay))
activeImage();
if(active==false)
return;
if(timer.wait(delay))
return;
GameWorld world=(GameWorld)getWorld();
world.addObject(new Snake(posX,0,0),world.getScrollx()+360+posX,0);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class HealthBar here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class HealthBar extends Actor
{
private int health;
private Timer timer=new Timer();
public HealthBar()
{
health=100;
setImage("healthbar100.png");
timer.reset();
}
public void act()
{
timer.tick();
if(health>10)
{
setLocation(110,130);
timer.reset();
}
else
if(health==10)
{
if(getY()>130)
{
if(!timer.wait(100))
setLocation(110,125);
}
else
if(!timer.wait(100))
setLocation(110,135);
}
}
public void updateImage(int h)
{
GameWorld world=(GameWorld)getWorld();
Player player=world.getPlayer();
health=h;
if(h>0)
setImage("healthbar"+health+".png");
else
setImage("healthbar0.png");
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Background here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Background extends Actor
{
int index;
int terrainNum;
/**
* Creates a new Ground which the player can stand on. Receives the index.
*/
public Background(int num)
{
index=num;
terrainNum=1;
//loadImages();
//setSkin();
}
/*public void loadImages()
{
for(int i=0;i<=10;i++)
{
images[i]=new GreenfootImage("background_jungle"+i+".png");
}
}*/
public void act()
{
setSkin();
GameWorld world=(GameWorld)getWorld();
int scrollx=world.getScrollx();
int width=world.getWidth();
int num=world.getTerrainNum();
setLocation(scrollx+width*index,world.getHeight()/2);
if(terrainNum<num)
{
index--;
terrainNum=num;
}else
if(terrainNum>num)
{
index++;
terrainNum=num;
}
}
public void setSkin()
{
setImage(((GameWorld)getWorld()).getImage(2,index));
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Next here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Next extends Button
{
public Next(int x,int y)
{
super(x,y);
setImage(new GreenfootImage("next0.png"));
}
public void act()
{
super.act();
if(isMouseOver())
{
setImage(new GreenfootImage("next1.png"));
if(clicked())
((GameWorld)getWorld()).nextPage();
}
else
setImage(new GreenfootImage("next0.png"));
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
/**
* Write a description of class Lives here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Lives extends Actor
{
public Lives()
{
setImage("hat.png");
updateImage(5);
}
public void act()
{
setLocation(getImage().getWidth()/2+20,getY());
}
public void updateImage(int lives)
{
if(lives<=0)
{
GreenfootImage image=new GreenfootImage(40,30);
image.setColor(new Color(0,0,0,0));
image.fill();
setImage(image);
return;
}
GreenfootImage image=new GreenfootImage(40*lives,30);
GreenfootImage hat=new GreenfootImage("hat.png");
for(int i=0;i<lives;i++)
image.drawImage(hat,40*i,0);
setImage(image);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Ground here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Ground extends Actor
{
int index;
int terrainNum;
/**
* Creates a new Ground which the player can stand on. Receives the index.
*/
public Ground(int num)
{
index=num;
terrainNum=1;
//loadImages();
//setSkin();
}
/*public void loadImages()
{
for(int i=0;i<=10;i++)
{
images[i]=new GreenfootImage("ground_jungle"+i+".png");
}
}*/
public void act()
{
setSkin();
GameWorld world=(GameWorld)getWorld();
int scrollx=world.getScrollx();
int width=world.getWidth();
int num=world.getTerrainNum();
setLocation(scrollx+width*index,world.getHeight()/2);
if(terrainNum<num)
{
index--;
terrainNum=num;
}else
if(terrainNum>num)
{
index++;
terrainNum=num;
}
}
public void setSkin()
{
setImage(((GameWorld)getWorld()).getImage(1,index));
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
import java.awt.Font;
/**
* Write a description of class Display here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Display extends Actor
{
public Display(String message)
{
GreenfootImage image=new GreenfootImage(message.length()*16,100);
image.clear();
image.setColor(new Color(0,0,0,0));
image.fill();
image.setColor(new Color(255,255,255,255));
image.setFont(new Font("Impact",Font.PLAIN,32));
image.drawString(message,0,image.getHeight()/2+10);
setImage(image);
}
public Display(String message,int fontSize)
{
GreenfootImage image=new GreenfootImage(message.length()*fontSize/2,25);
image.clear();
image.setColor(new Color(0,0,0,100));
image.fill();
image.setColor(new Color(255,255,255,255));
image.setFont(new Font("Impact",Font.PLAIN,fontSize));
image.drawString(message,0,image.getHeight()/2+10);
setImage(image);
}
public void act()
{
// Add your action code here.
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Help here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Help extends Button
{
public Help(int x,int y)
{
super(x,y);
setImage(new GreenfootImage("help0.png"));
}
public void act()
{
super.act();
if(isMouseOver())
{
setImage(new GreenfootImage("help1.png"));
if(clicked())
((GameWorld)getWorld()).showHelp();
}
else
setImage(new GreenfootImage("help0.png"));
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Scores here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Scores extends Button
{
public Scores(int x,int y)
{
super(x,y);
setImage(new GreenfootImage("scores0.png"));
}
public void act()
{
super.act();
if(isMouseOver())
{
setImage(new GreenfootImage("scores1.png"));
if(clicked())
((GameWorld)getWorld()).showScores();
}
else
setImage(new GreenfootImage("scores0.png"));
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Credits here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Credits extends Button
{
public Credits(int x,int y)
{
super(x,y);
setImage(new GreenfootImage("credits0.png"));
}
public void act()
{
super.act();
if(isMouseOver())
{
setImage(new GreenfootImage("credits1.png"));
if(clicked())
((GameWorld)getWorld()).showCredits();
}
else
setImage(new GreenfootImage("credits0.png"));
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Rock here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Rock extends Trap
{
private int yVel=0;
private boolean exists;
private Timer spawnTimer=new Timer();
private CollisionBox colDown=new CollisionBox(this,0,30,10,10);
private boolean addedToWorld=false;
public Rock(int x,int del, int iniD,int skin)
{
super(x,del,iniD);
exists=false;
damage=10;
GreenfootImage image;
switch(skin)
{
case 1: image=new GreenfootImage("rock_jungle1.png");
break;
case 2: image=new GreenfootImage("rock_jungle2.png");
break;
default: image=new GreenfootImage("rock.png");
break;
}
image.setTransparency(0);
setImage(image);
setRotation(Greenfoot.getRandomNumber(360));
}
public void act()
{
timer.tick();
spawnTimer.tick();
activeTimer.tick();
GameWorld world=(GameWorld)getWorld();
if(addedToWorld==false)
{
addedToWorld=true;
world.addObject(colDown,getX(),getY());
}
int scrollx=world.getScrollx();
setLocation(scrollx+posX+360,getY());
if(active==true || !activeTimer.wait(initialDelay))
activeImage();
if(active==false)
return;
if(exists==false && !spawnTimer.wait(delay))
exists=true;
if(exists==false)
return;
/*if(getImage().getTransparency()==0)
{
GreenfootImage image=getImage();
image.setTransparency(255);
setImage(image);
}*/
Player player=getPlayer();
if(isTouchingPlayer() && !colDown.isTouchingGround())
player.getHurt(damage);
if(!colDown.isTouchingGround() && getY()<world.getHeight()+50)
fall();
else
disappear();
}
public void fall()
{
yVel+=1;
setLocation(getX(),getY()+yVel);
if(!timer.wait(50))
turn(10+Greenfoot.getRandomNumber(30));
}
public void disappear()
{
int scrollx=((GameWorld)getWorld()).getScrollx();
GreenfootImage image=getImage();
if(image.getTransparency()>50)
{
if(!timer.wait(100))
image.setTransparency(image.getTransparency()-50);
}else
{
image.setTransparency(0);
setLocation(scrollx+posX+getWorld().getWidth()/2,-10);
exists=false;
yVel=0;
}
setImage(image);
}
}
| Java |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Snake here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Snake extends Trap
{
private int yVel=0;
private int skinIndex=0;
private boolean isAlive=true;
private boolean jumpingSnake=false;
private int dir;
private int xVel;
private CollisionBox colDown=new CollisionBox(this,0,30,10,10);
private CollisionBox colSnake=new CollisionBox(this,0,0,90,90);
private boolean addedToWorld=false;
private boolean exists=true;
private GreenfootImage[][] skins=new GreenfootImage[3][2];
private static final int RIGHT=0;
private static final int LEFT=1;
public Snake(int x,int del,int iniD)
{
super(x,del,iniD);
xVel=10;
damage=10;
int ran=Greenfoot.getRandomNumber(5);
for(int i=0;i<3;i++)
{
skins[i][0]=new GreenfootImage("snake_"+ran+"_"+i+".png");
skins[i][1]=new GreenfootImage("snake_"+ran+"_"+i+".png");
skins[i][1].mirrorHorizontally();
}
switch(ran)
{
case 0: xVel=20;
break;
case 1: xVel=12;
damage=20;
break;
case 2: damage=20;
break;
case 3: damage=50;
xVel=5;
break;
default: xVel=14;
jumpingSnake=true;
break;
}
setImage(skins[0][0]);
}
public void act()
{
timer.tick();
activeTimer.tick();
GameWorld world=(GameWorld)getWorld();
if(addedToWorld==false)
{
addedToWorld=true;
world.addObject(colDown,getX(),getY());
world.addObject(colSnake,getX(),getY());
}
if(active==true || !activeTimer.wait(initialDelay))
activeImage();
if(active==false)
return;
if(colDown.isTouchingGround())
{
yVel=-1;
setLocation(getX(),world.getHeight()-120);
if(jumpingSnake && isAlive)
yVel-=10;
}
yVel+=1;
setLocation(world.getScrollx()+360+posX,getY()+yVel);
if(isAlive)
{
setLocation(world.getScrollx()+360+posX,getY());
if(isTouchingWhip())
{
isAlive=false;
skinIndex=2;
setImage(skins[skinIndex][dir]);
timer.reset();
}
if(isTouchingPlayer())
getPlayer().getHurt(damage);
if(timer.wait(100))
return;
if(getX()<getPlayer().getX())
{
posX+=xVel;
dir=RIGHT;
}
else
{
posX-=xVel;
dir=LEFT;
}
Whip whip=world.getWhip();
if(getY()>world.getHeight() || (isTouching(Trap.class) && !isTouching(Snake.class) && !isTouching(SnakeSpawner.class)))
{
isAlive=false;
skinIndex=2;
timer.reset();
}
if(skinIndex==0 && skinIndex<2)
skinIndex=1;
else
if(skinIndex<2)
skinIndex=0;
setImage(skins[skinIndex][dir]);
}else
disappear();
if(getImage().getTransparency()==0)
{
world.removeObject(this);
world.removeObject(colDown);
world.removeObject(colSnake);
}
}
public void disappear()
{
int scrollx=((GameWorld)getWorld()).getScrollx();
GreenfootImage image=getImage();
if(image.getTransparency()>50)
{
if(!timer.wait(100))
image.setTransparency(image.getTransparency()-25);
}else
{
image.setTransparency(0);
setLocation(scrollx+posX+getWorld().getWidth()/2,0);
exists=false;
}
setImage(image);
}
public boolean isTouchingWhip()
{
if(!intersects(((GameWorld)getWorld()).getWhip()))
return(false);
return(touch(((GameWorld)getWorld()).getWhip()));
}
public void kill()
{
isAlive=false;
}
}
| Java |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.quake;
import android.view.View;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Canvas;
public class QuakeViewNoData extends View {
public QuakeViewNoData(Context context, int reason)
{
super(context);
mReason = reason;
}
public static final int E_NODATA = 1;
public static final int E_INITFAILED = 2;
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(0xffffffff);
paint.setStyle(Paint.Style.FILL);
canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
paint.setColor(0xff000000);
switch(mReason)
{
case E_NODATA:
canvas.drawText("Missing data files. Looking for one of:",
10.0f, 20.0f, paint);
canvas.drawText("/sdcard/data/quake/id1/pak0.pak",
10.0f, 35.0f, paint);
canvas.drawText("/data/quake/id1/pak0.pak",
10.0f, 50.0f, paint);
canvas.drawText("Please copy a pak file to the device and reboot.",
10.0f, 65.0f, paint);
break;
case E_INITFAILED:
canvas.drawText("Quake C library initialization failed.",
10.0f, 20.0f, paint);
canvas.drawText("Try stopping and restarting the simulator.",
10.0f, 35.0f, paint);
break;
}
}
private int mReason;
}
| Java |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.quake;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
/**
* An implementation of SurfaceView that uses the dedicated surface for
* displaying an OpenGL animation. This allows the animation to run in a
* separate thread, without requiring that it be driven by the update mechanism
* of the view hierarchy.
*
* The application-specific rendering code is delegated to a GLView.Renderer
* instance.
*/
class QuakeView extends GLSurfaceView {
QuakeView(Context context) {
super(context);
init();
}
public QuakeView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// We want events.
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
}
public void setQuakeLib(QuakeLib quakeLib) {
mQuakeLib = quakeLib;
setRenderer(new QuakeRenderer());
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (!weWantThisKeyCode(keyCode)) {
return super.onKeyDown(keyCode, event);
}
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_RIGHT:
case KeyEvent.KEYCODE_ALT_LEFT:
mAltKeyPressed = true;
break;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
case KeyEvent.KEYCODE_SHIFT_LEFT:
mShiftKeyPressed = true;
break;
}
queueKeyEvent(QuakeLib.KEY_PRESS,
keyCodeToQuakeCode(keyCode));
return true;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (!weWantThisKeyCode(keyCode)) {
return super.onKeyUp(keyCode, event);
}
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_RIGHT:
case KeyEvent.KEYCODE_ALT_LEFT:
mAltKeyPressed = false;
break;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
case KeyEvent.KEYCODE_SHIFT_LEFT:
mShiftKeyPressed = false;
break; }
queueKeyEvent(QuakeLib.KEY_RELEASE,
keyCodeToQuakeCode(keyCode));
return true;
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
if (!mGameMode) {
return super.onTrackballEvent(event);
}
queueTrackballEvent(event);
return true;
}
private boolean weWantThisKeyCode(int keyCode) {
return (keyCode != KeyEvent.KEYCODE_VOLUME_UP) &&
(keyCode != KeyEvent.KEYCODE_VOLUME_DOWN) &&
(keyCode != KeyEvent.KEYCODE_SEARCH);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
queueMotionEvent(ev);
return true;
}
private int keyCodeToQuakeCode(int keyCode) {
int key = 0;
if (key >= sKeyCodeToQuakeCode.length) {
return 0;
}
if (mAltKeyPressed) {
key = sKeyCodeToQuakeCodeAlt[keyCode];
if (key == 0) {
key = sKeyCodeToQuakeCodeShift[keyCode];
if (key == 0) {
key = sKeyCodeToQuakeCode[keyCode];
}
}
} else if (mShiftKeyPressed) {
key = sKeyCodeToQuakeCodeShift[keyCode];
if (key == 0) {
key = sKeyCodeToQuakeCode[keyCode];
}
} else {
key = sKeyCodeToQuakeCode[keyCode];
}
if (key == 0) {
key = '$';
}
return key;
}
public void queueKeyEvent(final int type, final int keyCode) {
queueEvent(
new Runnable() {
public void run() {
mQuakeLib.event(type, keyCode);
}
});
}
public void queueMotionEvent(final MotionEvent ev) {
queueEvent(
new Runnable() {
public void run() {
mQuakeLib.motionEvent(ev.getEventTime(),
ev.getAction(),
ev.getX(), ev.getY(),
ev.getPressure(), ev.getSize(),
ev.getDeviceId());
}
});
}
public void queueTrackballEvent(final MotionEvent ev) {
queueEvent(
new Runnable() {
public void run() {
mQuakeLib.trackballEvent(ev.getEventTime(),
ev.getAction(),
ev.getX(), ev.getY());
}
});
}
private boolean mShiftKeyPressed;
private boolean mAltKeyPressed;
private static final int[] sKeyCodeToQuakeCode = {
'$', QuakeLib.K_ESCAPE, '$', '$', QuakeLib.K_ESCAPE, '$', '$', '0', // 0.. 7
'1', '2', '3', '4', '5', '6', '7', '8', // 8..15
'9', '$', '$', QuakeLib.K_UPARROW, QuakeLib.K_DOWNARROW, QuakeLib.K_LEFTARROW, QuakeLib.K_RIGHTARROW, QuakeLib.K_ENTER, // 16..23
'$', '$', '$', QuakeLib.K_HOME, '$', 'a', 'b', 'c', // 24..31
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', // 32..39
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', // 40..47
't', 'u', 'v', 'w', 'x', 'y', 'z', ',', // 48..55
'.', QuakeLib.K_ALT, QuakeLib.K_ALT, QuakeLib.K_SHIFT, QuakeLib.K_SHIFT, QuakeLib.K_TAB, ' ', '$', // 56..63
'$', '$', QuakeLib.K_ENTER, QuakeLib.K_BACKSPACE, '`', '-', '=', '[', // 64..71
']', '\\', ';', '\'', '/', QuakeLib.K_CTRL, '#', '$', // 72..79
QuakeLib.K_HOME, '$', QuakeLib.K_ESCAPE, '$', '$' // 80..84
};
private static final int sKeyCodeToQuakeCodeShift[] =
{
0, 0, 0, 0, 0, 0, 0, ')', // 0.. 7
'!', '@', '#', '$', '%', '^', '&', '*', // 8..15
'(', 0, 0, 0, 0, 0, 0, 0, // 16..23
0, 0, 0, 0, 0, 0, ']', 0, // 24..31
'\\', '_', '{', '}', ':', '-', ';', '"', // 32..39
'\'', '>', '<', '+', '=', 0, 0, '|', // 40..47
0, 0, '[', '`', 0, 0, QuakeLib.K_PAUSE, ';', // 48..55
0, 0, 0, 0, 0, 0, 0, 0, // 56..63
0, 0, 0, 0, 0, 0, 0, 0, // 64..71
0, 0, '?', '0', 0, QuakeLib.K_CTRL, 0, 0, // 72..79
0, 0, 0, 0, 0 // 80..84
};
private static final int sKeyCodeToQuakeCodeAlt[] =
{
0, 0, 0, 0, 0, 0, 0, QuakeLib.K_F10, // 0.. 7
QuakeLib.K_F1, QuakeLib.K_F2, QuakeLib.K_F3, QuakeLib.K_F4, QuakeLib.K_F5, QuakeLib.K_F6, QuakeLib.K_F7, QuakeLib.K_F8, // 8..15
QuakeLib.K_F9, 0, 0, 0, 0, 0, 0, 0, // 16..23
0, 0, 0, 0, 0, 0, 0, 0, // 24..31
0, 0, 0, 0, 0, 0, 0, 0, // 32..39
0, 0, 0, 0, 0, 0, 0, 0, // 40..47
QuakeLib.K_F11, 0, 0, 0, 0, QuakeLib.K_F12, 0, 0, // 48..55
0, 0, 0, 0, 0, 0, 0, 0, // 56..63
0, 0, 0, 0, 0, 0, 0, 0, // 64..71
0, 0, 0, 0, 0, 0, 0, 0, // 72..79
0, 0, 0, 0, 0 // 80..83
};
private class QuakeRenderer implements GLSurfaceView.Renderer {
public void onDrawFrame(GL10 gl) {
if (mWidth != 0 && mHeight != 0) {
mGameMode = mQuakeLib.step(mWidth, mHeight);
}
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
mWidth = width;
mHeight = height;
mQuakeLib.init();
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Do nothing.
}
private int mWidth;
private int mHeight;
}
private QuakeLib mQuakeLib;
private boolean mGameMode;
}
| Java |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.quake;
// Wrapper for native quake application
public class QuakeLib {
public static final int KEY_PRESS = 1;
public static final int KEY_RELEASE = 0;
public static final int MOTION_DOWN = 0;
public static final int MOTION_UP = 1;
public static final int MOTION_MOVE = 2;
public static final int MOTION_CANCEL = 3;
// copied from Quake keys.h
// these are the key numbers that should be passed to Key_Event
//
//
// these are the key numbers that should be passed to Key_Event
//
public static final int K_TAB = 9;
public static final int K_ENTER = 13;
public static final int K_ESCAPE = 27;
public static final int K_SPACE = 32;
// normal keys should be passed as lowercased ascii
public static final int K_BACKSPACE = 127;
public static final int K_UPARROW = 128;
public static final int K_DOWNARROW = 129;
public static final int K_LEFTARROW = 130;
public static final int K_RIGHTARROW = 131;
public static final int K_ALT = 132;
public static final int K_CTRL = 133;
public static final int K_SHIFT = 134;
public static final int K_F1 = 135;
public static final int K_F2 = 136;
public static final int K_F3 = 137;
public static final int K_F4 = 138;
public static final int K_F5 = 139;
public static final int K_F6 = 140;
public static final int K_F7 = 141;
public static final int K_F8 = 142;
public static final int K_F9 = 143;
public static final int K_F10 = 144;
public static final int K_F11 = 145;
public static final int K_F12 = 146;
public static final int K_INS = 147;
public static final int K_DEL = 148;
public static final int K_PGDN = 149;
public static final int K_PGUP = 150;
public static final int K_HOME = 151;
public static final int K_END = 152;
public static final int K_PAUSE = 255;
//
// mouse buttons generate virtual keys
//
public static final int K_MOUSE1 = 200;
public static final int K_MOUSE2 = 201;
public static final int K_MOUSE3 = 202;
//
// joystick buttons
//
public static final int K_JOY1 = 203;
public static final int K_JOY2 = 204;
public static final int K_JOY3 = 205;
public static final int K_JOY4 = 206;
//
// aux keys are for multi-buttoned joysticks to generate so they can use
// the normal binding process
//
public static final int K_AUX1 = 207;
public static final int K_AUX2 = 208;
public static final int K_AUX3 = 209;
public static final int K_AUX4 = 210;
public static final int K_AUX5 = 211;
public static final int K_AUX6 = 212;
public static final int K_AUX7 = 213;
public static final int K_AUX8 = 214;
public static final int K_AUX9 = 215;
public static final int K_AUX10 = 216;
public static final int K_AUX11 = 217;
public static final int K_AUX12 = 218;
public static final int K_AUX13 = 219;
public static final int K_AUX14 = 220;
public static final int K_AUX15 = 221;
public static final int K_AUX16 = 222;
public static final int K_AUX17 = 223;
public static final int K_AUX18 = 224;
public static final int K_AUX19 = 225;
public static final int K_AUX20 = 226;
public static final int K_AUX21 = 227;
public static final int K_AUX22 = 228;
public static final int K_AUX23 = 229;
public static final int K_AUX24 = 230;
public static final int K_AUX25 = 231;
public static final int K_AUX26 = 232;
public static final int K_AUX27 = 233;
public static final int K_AUX28 = 234;
public static final int K_AUX29 = 235;
public static final int K_AUX30 = 236;
public static final int K_AUX31 = 237;
public static final int K_AUX32 = 238;
// JACK: Intellimouse(c) Mouse Wheel Support
public static final int K_MWHEELUP = 239;
public static final int K_MWHEELDOWN = 240;
static {
System.loadLibrary("quake");
}
public QuakeLib() {
}
public native boolean init();
/**
* Used to report key events
* @param type KEY_PRESS or KEY_RELEASE
* @param value the key code.
* @return true if the event was handled.
*/
public native boolean event(int type, int value);
/**
* Used to report touch-screen events
* @param eventTime the time the event happened
* @param action the kind of action being performed -- one of either
* {@link #MOTION_DOWN}, {@link #MOTION_MOVE}, {@link #MOTION_UP},
* or {@link #MOTION_CANCEL}
* @param x the x coordinate in pixels
* @param y the y coordinate in pixels
* @param pressure the pressure 0..1, can be more than 1 sometimes
* @param size the size of the area pressed (radius in X or Y)
* @param deviceId the id of the device generating the events
* @return true if the event was handled.
*/
public native boolean motionEvent(long eventTime, int action,
float x, float y, float pressure, float size, int deviceId);
/**
* Used to report trackball events
* @param eventTime the time the event happened
* @param action the kind of action being performed -- one of either
* {@link #MOTION_DOWN}, {@link #MOTION_MOVE}, {@link #MOTION_UP},
* or {@link #MOTION_CANCEL}
* @param x the x motion in pixels
* @param y the y motion in pixels
* @return true if the event was handled.
*/
public native boolean trackballEvent(long eventTime, int action,
float x, float y);
/**
* @param width the current view width
* @param height the current view height
* @return true if quake is in "game" mode, false if it is in "menu" or
* "typing" mode.
*/
public native boolean step(int width, int height);
/**
* Tell Quake to quit. It will write out its config files and so forth.
*/
public native void quit();
}
| Java |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.quake;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import java.io.File;
public class QuakeActivity extends Activity {
QuakeView mQuakeView;
static QuakeLib mQuakeLib;
boolean mKeepScreenOn = true;
@Override protected void onCreate(Bundle icicle) {
Log.i("QuakeActivity", "onCreate");
super.onCreate(icicle);
if (foundQuakeData()) {
if (mQuakeLib == null) {
mQuakeLib = new QuakeLib();
if(! mQuakeLib.init()) {
setContentView(new QuakeViewNoData(
getApplication(),
QuakeViewNoData.E_INITFAILED));
return;
}
}
if (mKeepScreenOn) {
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
if (mQuakeView == null) {
mQuakeView = new
QuakeView(getApplication());
mQuakeView.setQuakeLib(mQuakeLib);
}
setContentView(mQuakeView);
}
else {
setContentView(new QuakeViewNoData(getApplication(),
QuakeViewNoData.E_NODATA));
}
}
@Override protected void onPause() {
super.onPause();
if (mQuakeView != null) {
mQuakeView.onPause();
}
}
@Override protected void onResume() {
super.onResume();
if (mQuakeView != null) {
mQuakeView.onResume();
}
}
@Override protected void onDestroy() {
super.onDestroy();
if (mQuakeLib != null) {
mQuakeLib.quit();
}
}
private boolean foundQuakeData() {
return fileExists(SDCARD_DATA_PATH + PAK0_PATH)
|| fileExists(INTERNAL_DATA_PATH + PAK0_PATH);
}
private boolean fileExists(String s) {
File f = new File(s);
return f.exists();
}
private final static String SDCARD_DATA_PATH = "/sdcard/data/quake";
private final static String INTERNAL_DATA_PATH = "/data/quake";
private final static String PAK0_PATH = "/id1/pak0.pak";
}
| Java |
package com.project;
import java.util.Collection;
import java.util.TreeMap;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
/**
* Implementation of a Trie node and contains everything we need to be able to implement our trie and GUI.
* @author Anthony and Kevin
*
*/
public class TrieNode extends DefaultMutableTreeNode{
/**
*
*/
private static final long serialVersionUID = 1L;
private char character;
private String string;
private TrieNode parent;
/**
* My basic idea for a TrieNode, change as you see fit.
*/
private TreeMap<Character, TrieNode> children;
private int value;
public TrieNode(char c, String name, TrieNode parent){
super(name);
children = new TreeMap<Character,TrieNode>();
value = -1;
this.character = c;
string = null;
this.parent = parent;
}
public int getValue(){
return value;
}
public void setValue(int value){
this.value = value;
}
public TrieNode getChild(char c){
return children.get(c);
}
public void giveChild(char c, DefaultTreeModel model){
TrieNode newNode = new TrieNode(c, c + "", this);
children.put(c, newNode);
super.add(newNode);
model.insertNodeInto(newNode, this, children.size() - 1);
}
public boolean hasChild(char c){
return children.containsKey(c);
}
public int numChildren(){
return children.size();
}
public void removeChild(char c, DefaultTreeModel model){
TrieNode node = children.get(c);
model.removeNodeFromParent(node);
children.remove(c);
}
public Collection<TrieNode> getAllChildren(){
return children.values();
}
public char getCharacter(){
return character;
}
public void setString(String s){
this.string = s;
}
public String getString(){
return string;
}
}
| Java |
package com.project;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
@SuppressWarnings("serial")
public class TreePanel extends JFrame implements TreeSelectionListener{
private JPanel treepane;
private JPanel detailpane;
private JPanel inputpane;
TrieNode root;
/**
* Initializes our GUI and sets the title for the application
*/
public TreePanel() {
this.setLayout(new BorderLayout());
this.setTitle("Trie");
detailpane = new DetailPanel(this);
treepane = new TreeDisplay(this);
inputpane = new InputPanel((TreeDisplay) treepane);
add(treepane, BorderLayout.WEST);
add(detailpane, BorderLayout.EAST);
add(inputpane, BorderLayout.SOUTH);
}
@Override
public void valueChanged(TreeSelectionEvent arg0) {
// TODO Auto-generated method stub
}
}
| Java |
package com.project;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
@SuppressWarnings("serial")
public class DetailPanel extends JPanel{
private static JFrame tree;
private static JTextArea output;
private static String text;
public DetailPanel(TreePanel tree){
DetailPanel.tree = tree;
this.setPreferredSize(new Dimension(500,25));
output = new JTextArea(25,40);
output.setEditable(false);
JScrollPane pane = new JScrollPane(output);
text = new String("Trie Implementation:\n");
output.setText(text);
add(pane);
}
/**
* Allows anyone to print to the detail panel on the right side of the screen.
* @param text
*/
public static void addText(String text){
output.append(text + "\n");
}
}
| Java |
package com.project;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
@SuppressWarnings("serial")
public class TreeDisplay extends JPanel implements TreeSelectionListener {
private static JTree tree;
private static TrieNode root;
private static DefaultTreeModel model;
// JScrollPane panel;
JFrame trees;
static Map<String, Integer> entries = new HashMap<String,Integer>();
public TreeDisplay(TreePanel trees) {
this.trees = trees;
root = new TrieNode('a',"Trie", null);
model = new DefaultTreeModel(root);
tree = new JTree(model);
JScrollPane panel = new JScrollPane(tree);
panel.setPreferredSize(new Dimension(500,400));
add(panel);
}
/**
* Adds the name and value to the trie.
* @param name
* @param value
*/
public void addToTrie(String name, int value) {
TrieNode temp = root;
int i = 0;
entries.put(name,value);
while (temp.hasChild(name.charAt(i))){
temp = temp.getChild(name.charAt(i));
i++;
if (i>=name.length()){
break;
}
}
if (i == name.length()){
temp.setString(name);
temp.setValue(value);
}
else {
if (i==0) {
while(i<name.length()){
temp.giveChild(name.charAt(i),model);
temp = temp.getChild(name.charAt(i));
i++;
}
temp.setString(name);
temp.setValue(value);
}
else {
while(i<name.length()){
temp.giveChild(name.charAt(i), model);
temp = temp.getChild(name.charAt(i));
i++;
}
temp.setString(name);
temp.setValue(value);
}
}
}
/**
* Makes a recursive call to find the key in the trie.
* @param key
* @return
*/
public int findInTrie(String key){
if(root.getAllChildren().isEmpty()){
return -1;
}
return findInTrie(root, key, 0);
}
private static int findInTrie(TrieNode node, String key, int index){
if(node == null){
return -1;
}
TrieNode child = node.getChild(key.charAt(index));
if(child != null){
index++;
if(index == key.length()){
TreePath pathToNode = new TreePath(child.getPath());
tree.scrollPathToVisible(pathToNode);
tree.setSelectionPath(pathToNode);
return child.getValue();
}
return findInTrie(child, key, index);
}
return -1;
}
/**
* Recursively removes the nodes in the tree until there is one or more child stemming from the node.
* @param key
* @return
*/
public int removeInTrie(String key){
if(root.getAllChildren().isEmpty()){
return -1;
}
return removeInTrie(root, key, 0);
}
private static int removeInTrie(TrieNode node, String key, int index){
if(node == null){
return -1;
}
TrieNode child = node.getChild(key.charAt(index));
char c = key.charAt(index);
if(child != null){
index++;
if(index == key.length()){
int val = child.getValue();
if(child.numChildren() == 0){
node.removeChild(c, model);
}else{
child.setValue(-1);
}
entries.remove(key);
return val;
}
int value = removeInTrie(child, key, index);
if(child.numChildren() == 0){
node.removeChild(c,model);
}
return value;
}
return -1;
}
/**
* Prints a preorder traversal of the list.
*/
public void preorderTraversal(){
DetailPanel.addText("Here is a sorted list of Strings in the Trie with their respective values.");
preorderTraversal(root);
}
private void preorderTraversal(TrieNode node){
TrieNode temp = node;
Collection<TrieNode> children = temp.getAllChildren();
if(children == null){
return;
}
for(TrieNode n: children){
preorderTraversal(n);
}
if(node.getValue() != -1){
DetailPanel.addText(node.getString() + " : " + node.getValue());
}
}
public void alphaSort(){
ArrayList<Entry<String,Integer>> sorted = new ArrayList<Entry<String,Integer>>();
Set<Entry<String, Integer>> names = entries.entrySet();
for (Entry<String,Integer> e: names) {
if (sorted.size() == 0)
sorted.add(e);
else {
sorted.add(e);
int i = sorted.size()-1;
while (((String) sorted.get(i).getKey()).compareTo(sorted.get(i-1).getKey()) < 0){
Entry<String, Integer> temp = sorted.get(i);
sorted.set(i, sorted.get(i-1));
sorted.set(i-1, temp);
i--;
if ((i-1) == -1){
break;
}
}
}
}
clearAll();
for (Entry<String,Integer> a: sorted){
addToTrie((String)a.getKey(),(Integer) a.getValue());
}
}
public void clearAll(){
removeAll(root, null);
entries = new HashMap<String,Integer>();
}
private static void removeAll(TrieNode node, TrieNode parent){
Collection<TrieNode> children = node.getAllChildren();
if(children == null){
return;
}
TrieNode[] nodes = children.toArray(new TrieNode[children.size()]);
for(int i = 0; i < nodes.length; i++){
removeAll(nodes[i], node);
}
if(children.size() == 0 && parent != null){
parent.removeChild(node.getCharacter(), model);
}
}
public void valSort() {
ArrayList<Entry<String,Integer>> sorted = new ArrayList<Entry<String,Integer>>();
Set<Entry<String, Integer>> names = entries.entrySet();
for (Entry<String,Integer> e: names) {
if (sorted.size() == 0)
sorted.add(e);
else {
sorted.add(e);
int i = sorted.size()-1;
while (((Integer) sorted.get(i).getValue()<
((Integer) sorted.get(i-1).getValue()))){
Entry<String, Integer> temp = sorted.get(i);
sorted.set(i, sorted.get(i-1));
sorted.set(i-1, temp);
i--;
if ((i-1) == -1){
break;
}
}
}
}
clearAll();
for (Entry<String,Integer> a: sorted){
addToTrie((String)a.getKey(),(Integer) a.getValue());
}
}
public Collection<String> autocomplete(String input){
if(input == null){
return new ArrayList<String>();
}
if(input.equals("")){
return new ArrayList<String>();
}
Collection<String> strings = new ArrayList<String>();
TrieNode start = autocomplete(root,input,0);
if(start == null){
return new ArrayList<String>();
}
if(start.getValue() != -1){
strings.add(input);
}
if(!start.getAllChildren().isEmpty()){
allOutcomes(start,input,strings);
}
return strings;
}
private static void allOutcomes(TrieNode node, String key, Collection<String> strings){
for(TrieNode n: node.getAllChildren()){
String newKey = key + n.getCharacter();
if(n.getValue() != -1){
strings.add(newKey);
}
allOutcomes(n,newKey,strings);
}
}
private static TrieNode autocomplete(TrieNode node, String key, int index){
if(node == null){
return null;
}
TrieNode child = node.getChild(key.charAt(index));
if(child != null){
index++;
if(index == key.length()){
//TreePath pathToNode = new TreePath(child.getPath());
//tree.scrollPathToVisible(pathToNode);
//tree.setSelectionPath(pathToNode);
return child;
}
return autocomplete(child, key, index);
}
return null;
}
@Override
public void valueChanged(TreeSelectionEvent arg0) {
// TODO Auto-generated method stub
}
}
| Java |
package com.project;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
@SuppressWarnings("serial")
public class InputPanel extends JPanel{
JButton adding;
JButton remove;
JButton find;
JButton print;
JButton alphSort;
JButton valSort;
JButton clear;
JButton autocomplete;
JTextField addfield;
JTextField valueField;
JTextField removefield;
JTextField findfield;
JTextField autocompleteField;
TreeDisplay tree;
public InputPanel(TreeDisplay tree) {
this.tree = tree;
// setSize(100, 50);
adding = new JButton("Add");
adding.addActionListener(new ButtonListener(0));
remove = new JButton("Remove");
remove.addActionListener(new ButtonListener(1));
find = new JButton("Find");
find.addActionListener(new ButtonListener(2));
print = new JButton("Print all Students!");
print.addActionListener(new ButtonListener(3));
alphSort = new JButton("Sort Tree By Letter");
alphSort.addActionListener(new ButtonListener(4));
valSort = new JButton("Sort Tree By Value ");
valSort.addActionListener(new ButtonListener(5));
clear = new JButton("Clear Tree");
clear.addActionListener(new ButtonListener(6));
autocomplete = new JButton("Autocomplete Suggestions:");
autocomplete.addActionListener(new ButtonListener(7));
addfield = new JTextField(5);
valueField = new JTextField(5);
removefield = new JTextField(10);
findfield = new JTextField(10);
autocompleteField = new JTextField(10);
add(alphSort);
add(valSort);
add(adding);
add(addfield);
add(valueField);
add(remove);
add(removefield);
add(find);
add(findfield);
add(print);
add(clear);
// add(autocomplete);
// add(autocompleteField);
}
class ButtonListener implements ActionListener {
int action;
public ButtonListener(int action) {
this.action = action;
}
public void actionPerformed(ActionEvent e) {
switch (action) {
//case 0 is when the add button is pressed. Adds the String and value into the trie.
case 0:
if(addfield.getText().equals("") || addfield.getText() == null){
DetailPanel.addText("Please enter a valid string to add to the trie");
return;
}
int value;
try{
value = Integer.parseInt(valueField.getText());
}catch(NumberFormatException n){
DetailPanel.addText("Please enter a number for the value");
return;
}
((TreeDisplay) tree).addToTrie(addfield.getText(), value);
DetailPanel.addText("The String you added was: "+ addfield.getText() + " and the value inputted was: " + valueField.getText());
addfield.setText("");
valueField.setText("");
break;
//case 1 is when the remove button is pressed. Removes the string if it exists and displays the value it had.
case 1:
value = tree.removeInTrie(removefield.getText());
if(value == -1){
DetailPanel.addText("The String you inputted DOES NOT EXIST. Please try again.");
}else{
DetailPanel.addText("The String you removed is: " + removefield.getText()
+ " and its value was: " + value);
}
removefield.setText("");
break;
//case 2 is when the find button is pressed. Highlights the path to the node if it exists and displays the value.
case 2:
String text = findfield.getText();
if (text.isEmpty()) {
DetailPanel.addText("Please enter the string you would like to find.");
}
else{
int val = tree.findInTrie(text);
if(val == -1){
Collection<String> strings = tree.autocomplete(text);
if(strings.isEmpty()){
DetailPanel.addText("The String was not found in the Trie");
}else{
DetailPanel.addText("Did you mean one of these below?");
for(String s: strings){
DetailPanel.addText(s);
}
}
}else{
DetailPanel.addText("The String you inputted has been expanded and highlighted. Its value is: " + val);
}
}
break;
//runs a preorder traversal on the tree which displays the strings in lexographically sorted order.
case 3: tree.preorderTraversal();
break;
case 4:
tree.alphaSort();
break;
case 5:
tree.valSort();
break;
case 6:
tree.clearAll();
DetailPanel.addText("You have cleared the entire Tree");
break;
/*case 7:
Collection<String> strings = tree.autocomplete(autocompleteField.getText());
if(strings.isEmpty()){
DetailPanel.addText("No suggestions have been found for the inputted text.");
}else{
DetailPanel.addText("The following suggestions were found:");
for(String s: strings){
DetailPanel.addText(s);
}
}
break;*/
}
}
}
}
| Java |
package com.project;
import javax.swing.JFrame;
public class TrieDriver {
/**
* Runs the GUI for our Trie
* @param args
*/
public static void main(String[] args) {
TreePanel treePanel = new TreePanel();
treePanel.setSize(500, 500);
treePanel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
treePanel.setResizable(true);
treePanel.setVisible(true);
treePanel.pack();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package client;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import server.User;
/**
*
* @author huy
*/
public class NonblockingClient {
private void invoke() {
TTransport transport;
try {
transport = new TFramedTransport(new TSocket("localhost", 7911));
TProtocol protocol = new TBinaryProtocol(transport);
User.Client client = new User.Client(protocol);
transport.open();
/*Gọi các phương thức trong service tại đây*/
System.out.println(client.listTag());
transport.close();
} catch (TTransportException e) {
} catch (TException e) {
}
}
public static void main(String[] args) {
NonblockingClient c = new NonblockingClient();
c.invoke();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import DAO.StatusDAO;
import DAO.TagDAO;
import DAO.UserDAO;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
/**
*
* @author huy
*/
public class UserImpl implements User.Iface{
private TTransport tr;
private Cassandra.Client client;
public UserImpl()
{
try {
tr = new TFramedTransport(new TSocket(common.Constants.HOST, common.Constants.PORT));
TProtocol proto = new TBinaryProtocol(tr);
client = new Cassandra.Client(proto);
tr.open();
client.set_keyspace(common.Constants.KEYSPACE);
} catch (InvalidRequestException ex) {
Logger.getLogger(UserImpl.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(UserImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public String selectRandom(){
StatusDAO status_DAO = StatusDAO.getInstance(client);
String result = status_DAO.SelectRandom();
//tr.close();
return result;
}
@Override
public String selectRandomtoTag(String NameTag){
StatusDAO status_DAO = StatusDAO.getInstance(client);
String result = status_DAO.SelectRandomtoTag(NameTag);
//tr.close();
return result;
}
@Override
public boolean savefavoriteStatus(String UseriD, String StatusID){
UserDAO user_DAO = UserDAO.getInstance(client);
boolean result = user_DAO.savefavoriteStatus(UseriD, StatusID);
//tr.close();
return result;
}
@Override
public String selectfavoriteStatus(String UserID){
UserDAO user_DAO = UserDAO.getInstance(client);
String result = user_DAO.selectfavoriteStatus(UserID);
//tr.close();
return result;
}
@Override
public boolean deletefavoriteStatus(String UserID, String StatusID){
UserDAO user_DAO = UserDAO.getInstance(client);
boolean result = user_DAO.deletefavoriteStatus(UserID, StatusID);
//tr.close();
return result;
}
@Override
public String listOutstandingStatus(){
StatusDAO status_DAO = StatusDAO.getInstance(client);
String result = status_DAO.listOutstandingStatus();
//tr.close();
return result;
}
@Override
public boolean inscreaseLikecount(String StatusID){
StatusDAO status_DAO = StatusDAO.getInstance(client);
boolean result = status_DAO.increaseLikecount(StatusID);
//tr.close();
return result;
}
@Override
public boolean inscreaseDislikecount(String StatusID){
StatusDAO status_DAO = StatusDAO.getInstance(client);
boolean result = status_DAO.increaseDislikecount(StatusID);
//tr.close();
return result;
}
@Override
public String listTag(){
TagDAO tag_DAO = TagDAO.getInstance(client);
String result = tag_DAO.PrintALLTag_S();
//tr.close();
return result;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TNonblockingServerTransport;
import org.apache.thrift.transport.TTransportException;
/**
*
* @author huy
*/
public class NonblockingServer {
private void start() {
try {
TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(7911);
User.Processor processor = new User.Processor(new UserImpl());
TServer server = new TNonblockingServer(new TNonblockingServer.Args(serverTransport).
processor(processor));
System.out.println("Starting server on port 7911 ...");
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
NonblockingServer srv = new NonblockingServer();
srv.start();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pojo;
import java.util.List;
/**
*
* @author tipuder
*/
public class User {
public static String col_favorite = "list_status_ID";
public static String col_parent = "FavoriteStatus";
private String user_ID;
private List<String> list_status_ID;
public User() {
}
public User(String user_ID, List<String> list_status_ID) {
this.user_ID = user_ID;
this.list_status_ID = list_status_ID;
}
public static String getCol_favorite() {
return col_favorite;
}
public static void setCol_favorite(String col_favorite) {
User.col_favorite = col_favorite;
}
public List<String> getList_status_ID() {
return list_status_ID;
}
public void setList_status_ID(List<String> list_status_ID) {
this.list_status_ID = list_status_ID;
}
public String getUser_ID() {
return user_ID;
}
public void setUser_ID(String user_ID) {
this.user_ID = user_ID;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pojo;
/**
*
* @author tipuder
*/
public class Status {
public static String colname_content = "content";
public static String colname_tags = "tags";
public static String colname_likecount = "like_count";
public static String colname_dislikecount = "dislike_count";
public static String colname_createdate = "create_date";
public static String colname_modifydate = "modify_date";
public static String colname_state = "state";
public static String col_parent = "Status";
private String status_ID;
private String content;
private String create_date;
private String dislike_count;
private String like_count;
private String modify_date;
private String state;
private String tags;
public Status() {
}
public Status(String status_ID, String content, String create_date, String dislike_count, String like_count, String modify_date, String state, String tags) {
this.status_ID = status_ID;
this.content = content;
this.create_date = create_date;
this.dislike_count = dislike_count;
this.like_count = like_count;
this.modify_date = modify_date;
this.state = state;
this.tags = tags;
}
public String getContent() {
return content;
}
public String getCreate_date() {
return create_date;
}
public String getDislike_count() {
return dislike_count;
}
public String getLike_count() {
return like_count;
}
public String getModify_date() {
return modify_date;
}
public String getState() {
return state;
}
public String getStatus_ID() {
return status_ID;
}
public String getTags() {
return tags;
}
public void setContent(String content) {
this.content = content;
}
public void setCreate_date(String create_date) {
this.create_date = create_date;
}
public void setDislike_count(String dislike_count) {
this.dislike_count = dislike_count;
}
public void setLike_count(String like_count) {
this.like_count = like_count;
}
public void setModify_date(String modify_date) {
this.modify_date = modify_date;
}
public void setState(String state) {
this.state = state;
}
public void setStatus_ID(String status_ID) {
this.status_ID = status_ID;
}
public void setTags(String tags) {
this.tags = tags;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pojo;
import java.util.List;
/**
*
* @author tipuder
*/
public class Tag {
public static String name_col_cdate = "create_date";
public static String name_col_mdate = "modify_date";
public static String name_col_state = "state";
public static String name_scol_lstatus = "list_status_ID";
public static String name_scol_info = "info_tag";
public static String col_parent = "Tag";
private String name_tag;
private List<String> list_status_ID;
private String create_date;
private String modify_date;
private String state;
public static String getCol_parent() {
return col_parent;
}
public static void setCol_parent(String col_parent) {
Tag.col_parent = col_parent;
}
public Tag() {
}
public String getCreate_date() {
return create_date;
}
public void setCreate_date(String create_date) {
this.create_date = create_date;
}
public List<String> getList_status_ID() {
return list_status_ID;
}
public void setList_status_ID(List<String> list_status_ID) {
this.list_status_ID = list_status_ID;
}
public String getModify_date() {
return modify_date;
}
public void setModify_date(String modify_date) {
this.modify_date = modify_date;
}
public static String getName_col_cdate() {
return name_col_cdate;
}
public static void setName_col_cdate(String name_col_cdate) {
Tag.name_col_cdate = name_col_cdate;
}
public static String getName_col_mdate() {
return name_col_mdate;
}
public static void setName_col_mdate(String name_col_mdate) {
Tag.name_col_mdate = name_col_mdate;
}
public static String getName_col_state() {
return name_col_state;
}
public static void setName_col_state(String name_col_state) {
Tag.name_col_state = name_col_state;
}
public String getName_tag() {
return name_tag;
}
public void setName_tag(String name_tag) {
this.name_tag = name_tag;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Tag(String name_tag, List<String> list_status_ID, String create_date, String modify_date, String state) {
this.name_tag = name_tag;
this.list_status_ID = list_status_ID;
this.create_date = create_date;
this.modify_date = modify_date;
this.state = state;
}
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package common;
import org.apache.cassandra.thrift.ConsistencyLevel;
/**
*
* @author tipuder
*/
public class Constants {
public static final String UTF8 = "UTF8";
public static final String KEYSPACE = "NghiNhanhDB2";
public static final ConsistencyLevel CL = ConsistencyLevel.ONE;
public static final String HOST = "localhost";
public static final int PORT = 9160;
public static int countStatus;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package common;
import static common.Constants.UTF8;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.cassandra.thrift.Column;
import pojo.Status;
import pojo.Tag;
/**
*
* @author tipuder
*/
public class GeneralHandling {
public static Column createCol(String name, String value)
{
Column result = new Column();
long time = System.currentTimeMillis();
try {
result = new Column(toByteBuffer(name));
if (name.equals(Status.colname_createdate) || name.equals(Tag.name_col_cdate))
{ Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
result.setValue(toByteBuffer(sdf.format(cal.getTime())));
}
else
result.setValue(toByteBuffer(value));
result.setTimestamp(time);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(GeneralHandling.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public static ByteBuffer toByteBuffer(String value)
throws UnsupportedEncodingException
{
return ByteBuffer.wrap(value.getBytes(UTF8));
}
public static String toString(ByteBuffer buffer)
throws UnsupportedEncodingException
{
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
return new String(bytes, UTF8);
}
public static int toInt(ByteBuffer buffer)
throws UnsupportedEncodingException
{
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
String temp = new String(bytes, UTF8);
return Integer.parseInt(temp);
}
public static java.util.UUID getTimeUUID()
{
return java.util.UUID.fromString(new com.eaio.uuid.UUID().toString());
}
/**
* Returns an instance of uuid.
*
* @param uuid the uuid
* @return the java.util. uuid
*/
public static java.util.UUID toUUID( byte[] uuid )
{
long msb = 0;
long lsb = 0;
assert uuid.length == 16;
for (int i=0; i<8; i++)
msb = (msb << 8) | (uuid[i] & 0xff);
for (int i=8; i<16; i++)
lsb = (lsb << 8) | (uuid[i] & 0xff);
long mostSigBits = msb;
long leastSigBits = lsb;
com.eaio.uuid.UUID u = new com.eaio.uuid.UUID(msb,lsb);
return java.util.UUID.fromString(u.toString());
}
/**
* As byte array.
*
* @param uuid the uuid
*
* @return the byte[]
*/
public static byte[] asByteArray(java.util.UUID uuid)
{
long msb = uuid.getMostSignificantBits();
long lsb = uuid.getLeastSignificantBits();
byte[] buffer = new byte[16];
for (int i = 0; i < 8; i++) {
buffer[i] = (byte) (msb >>> 8 * (7 - i));
}
for (int i = 8; i < 16; i++) {
buffer[i] = (byte) (lsb >>> 8 * (7 - i));
}
return buffer;
}
}
| Java |
package DAO;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.cassandra.thrift.*;
import org.apache.thrift.TException;
import pojo.User;
public class UserDAO {
private static Cassandra.Client client;
private static UserDAO instance;
public static UserDAO getInstance(Cassandra.Client _client)
{
if (instance != null)
return instance;
instance = new UserDAO();
client = _client;
return instance;
}
/*
public boolean savefavoriteStatus_T(String UserID,String StatusID)
{
boolean result = false;
try {
ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(UserID);
ColumnPath path = new ColumnPath(User.col_parent);
path.super_column = common.GeneralHandling.toByteBuffer(User.col_favorite);
//Kiểm tra xem UserID đã được insert chưa bằng cách lấy hết UserID lên so sánh.
ColumnParent parent = new ColumnParent(User.col_parent);
SlicePredicate predicate = new SlicePredicate();
predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(User.col_favorite));
KeyRange range = new KeyRange();
range.start_key = common.GeneralHandling.toByteBuffer("");
range.end_key = common.GeneralHandling.toByteBuffer("");
List<KeySlice> list = client.get_range_slices(parent, predicate, range, common.Constants.CL);
SuperColumn supercol = new SuperColumn();
supercol.setName(common.GeneralHandling.toByteBuffer(User.col_favorite));
for (KeySlice keySlice : list) {
if (keySlice.key == common.GeneralHandling.toByteBuffer(UserID))
{
supercol = (client.get(rowkey, path, common.Constants.CL)).super_column;
break;
}
}
supercol.addToColumns(common.GeneralHandling.createCol(StatusID, ""));
Addsupercolumn(rowkey, supercol);
result = true;
} catch (InvalidRequestException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (NotFoundException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public String selectfavoriteStatus_T(String UserID)
{
String result = "";
try {
ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(UserID);
ColumnPath path = new ColumnPath(User.col_parent);
path.super_column = common.GeneralHandling.toByteBuffer(User.col_favorite);
SuperColumn supercol = (client.get(rowkey, path, common.Constants.CL)).getSuper_column();
result = ParseToJSON(supercol);
} catch (InvalidRequestException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (NotFoundException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public boolean deletefavoriteStatus_T(String UserID, String statusID)
{
boolean result = false;
try {
ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(UserID);
ColumnPath path = new ColumnPath(User.col_parent);
path.super_column = common.GeneralHandling.toByteBuffer(User.col_favorite);
SuperColumn supercol = (client.get(rowkey, path, common.Constants.CL)).super_column;
SuperColumn newsupercol = new SuperColumn();
newsupercol.setName(supercol.name);
for (Column col : supercol.getColumns()) {
if (common.GeneralHandling.toString(col.name).equals(statusID))
{
col.value = common.GeneralHandling.toByteBuffer(" 1");
newsupercol.addToColumns(col);
}
else
newsupercol.addToColumns(col);
}
client.remove(rowkey, path, System.currentTimeMillis(), common.Constants.CL);
Addsupercolumn(rowkey, newsupercol);
result = true;
} catch (InvalidRequestException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (NotFoundException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public void Addsupercolumn(ByteBuffer rowkey, SuperColumn supercol)
{
try {
List<Mutation> mutations = new ArrayList<Mutation>();
ColumnOrSuperColumn colorsupcol = new ColumnOrSuperColumn();
Mutation m = new Mutation();
colorsupcol.setSuper_column(supercol);
m.setColumn_or_supercolumn(colorsupcol);
mutations.add(m);
Map<String, List<Mutation>> keyMutations = new HashMap<String, List<Mutation>>();
keyMutations.put(User.col_parent, mutations);
Map<ByteBuffer, Map<String, List<Mutation>>> mutationsMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
mutationsMap.put(rowkey, keyMutations);
client.batch_mutate(mutationsMap, common.Constants.CL);
} catch (InvalidRequestException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
*/
public boolean savefavoriteStatus(String UserID,String statusID)
{
boolean result = update(UserID,statusID,"0");
return result;
}
public boolean deletefavoriteStatus(String UserID, String statusID)
{
boolean result = update(UserID,statusID,"1");
return result;
}
public boolean update(String UserID, String statusID,String state)
{
boolean result = false;
try {
ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(UserID);
ColumnParent parent = new ColumnParent(User.col_parent);
Column col = common.GeneralHandling.createCol(statusID, state);
client.insert(rowkey, parent, col, common.Constants.CL);
result = true;
} catch (InvalidRequestException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public String selectfavoriteStatus(String UserID)
{
String result="";
try {
ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(UserID);
ColumnParent parent = new ColumnParent(User.col_parent);
SlicePredicate predicate = new SlicePredicate();
SliceRange range = new SliceRange();
range.start = common.GeneralHandling.toByteBuffer("");
range.finish = common.GeneralHandling.toByteBuffer("");
predicate.slice_range = range;
List<ColumnOrSuperColumn> listcol = client.get_slice(rowkey, parent, predicate, common.Constants.CL);
List<ByteBuffer> liststatusID = new ArrayList<ByteBuffer>();
for (ColumnOrSuperColumn columnOrSuperColumn : listcol) {
Column col = columnOrSuperColumn.getColumn();
String x = common.GeneralHandling.toString(col.value);
if (x.equals("0"))
liststatusID.add(col.name);
}
StatusDAO status_DAO = StatusDAO.getInstance(client);
result = status_DAO.Getliststatus(liststatusID);
} catch (InvalidRequestException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public String ParseToJSON(SuperColumn supercol) throws UnsupportedEncodingException
{
List<ByteBuffer> liststatusID = new ArrayList<ByteBuffer>();
for (Column col : supercol.getColumns()) {
if (!"1".equals(common.GeneralHandling.toString(col.value)))
liststatusID.add(col.name);
}
StatusDAO status_DAO = StatusDAO.getInstance(client);
String result = status_DAO.Getliststatus(liststatusID);
return result;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import static common.Constants.*;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
/**
*
* @author tipuder
*/
public class CassandraDataAccessHelper {
TTransport tr = new TSocket(HOST, PORT);
// returns a new connection to our keyspace
public Cassandra.Client connect() throws TTransportException,
TException, InvalidRequestException {
TFramedTransport tf = new TFramedTransport(tr);
TProtocol proto = new TBinaryProtocol(tf);
Cassandra.Client client = new Cassandra.Client(proto);
tr.open();
client.set_keyspace(KEYSPACE);
return client;
}
public void close() {
tr.close();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import common.GeneralHandling;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.cassandra.thrift.*;
import org.apache.thrift.TException;
import pojo.Status;
import pojo.Tag;
/**
*
* @author huy
*/
public class StatusDAO {
private static Cassandra.Client client;
private static StatusDAO instance;
public static StatusDAO getInstance(Cassandra.Client _client)
{
if (instance != null)
return instance;
instance = new StatusDAO();
client = _client;
return instance;
}
public boolean InsertStatus(Status newstatus)
{
boolean result = false;
try {
ColumnParent parent = new ColumnParent(Status.col_parent);
ByteBuffer status_ID = common.GeneralHandling.toByteBuffer(UUID.randomUUID().toString());
//Add các column vào CF.
client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_content, newstatus.getContent()),common.Constants.CL);
client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_tags, newstatus.getTags()),common.Constants.CL);
client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_likecount, newstatus.getLike_count()),common.Constants.CL);
client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_dislikecount, newstatus.getDislike_count()),common.Constants.CL);
client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_createdate, ""),common.Constants.CL);
client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_modifydate, ""),common.Constants.CL);
client.insert(status_ID,parent,GeneralHandling.createCol(Status.colname_state, "public"),common.Constants.CL);
//Cập nhật list_status_ID cho tag tương ứng.
String[] tags = newstatus.getTags().split(",");
TagDAO tag_DAO = TagDAO.getInstance(client);
String x = GeneralHandling.toString(status_ID);
for (int i = 0; i < tags.length; i++) {
if (!tag_DAO.InsertStatusIDtoTag(x, tags[i]))
return result;
}
result = true;
} catch (InvalidRequestException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public String SelectRandom()
{
String result = "";
try {
ColumnParent parent = new ColumnParent(Status.col_parent);
SlicePredicate predicate = new SlicePredicate();
predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_content));
predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_tags));
KeyRange range = new KeyRange();
range.start_key = common.GeneralHandling.toByteBuffer("");
range.end_key = common.GeneralHandling.toByteBuffer("");
List<KeySlice> p_listkey = client.get_range_slices(parent, predicate, range, common.Constants.CL);
int keystart = (new Random()).nextInt(/*common.Constants.countStatus*/70);
int count = (new Random()).nextInt(5) + 6;
List<KeySlice> listkey = p_listkey.subList(keystart, keystart + count);
result = ParseToJSON(listkey);
} catch (InvalidRequestException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public String SelectRandomtoTag(String Tagname)
{
String result = "";
try {
ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(Tagname);
ColumnParent parent = new ColumnParent(Tag.col_parent);
SlicePredicate predicate = new SlicePredicate();
predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Tag.name_scol_lstatus));
List<ColumnOrSuperColumn> result_key = client.get_slice(rowkey, parent, predicate, common.Constants.CL);
List<ByteBuffer> listStatusID = new ArrayList<ByteBuffer>();
for (ColumnOrSuperColumn col : result_key) {
for (Column c : col.getSuper_column().columns)
listStatusID.add(c.name);
}
//Xáo trôn list statusID
Random rd = new Random();
for (int i = 0; i < listStatusID.size() - 1; i++) {
for (int j = i + 1; j < listStatusID.size(); j++)
{
if (rd.nextInt(1) < rd.nextInt(3))
{
ByteBuffer temp = listStatusID.get(i);
listStatusID.set(i, listStatusID.get(j));
listStatusID.set(j, temp);
}
}
}
int length = rd.nextInt(5) + 6;
if (listStatusID.size() > length)
listStatusID = listStatusID.subList(0, length);
result = Getliststatus(listStatusID);
} catch (InvalidRequestException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public String Getliststatus(List<ByteBuffer> listStatusID)
{
String result = "";
try {
ColumnParent parent = new ColumnParent(Status.col_parent);
SlicePredicate predicate = new SlicePredicate();
predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_content));
predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_tags));
Map<ByteBuffer, List<ColumnOrSuperColumn>> mapstatus = client.multiget_slice(listStatusID, parent, predicate, common.Constants.CL);
List<KeySlice> liststatus = new ArrayList<KeySlice>();
for (int i = 0; i < mapstatus.size(); i++)
{
liststatus.add(new KeySlice(listStatusID.get(i), mapstatus.get(listStatusID.get(i))));
}
result = ParseToJSON(liststatus);
} catch (InvalidRequestException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
//Lấy danh sách 20 câu status nổi bật nhất
public String listOutstandingStatus()
{
String result = "";
try {
ColumnParent parent = new ColumnParent(Status.col_parent);
SlicePredicate predicate = new SlicePredicate();
predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_content));
predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_likecount));
predicate.addToColumn_names(common.GeneralHandling.toByteBuffer(Status.colname_dislikecount));
KeyRange keyrange = new KeyRange();
keyrange.start_key = common.GeneralHandling.toByteBuffer("");
keyrange.end_key = common.GeneralHandling.toByteBuffer("");
List<KeySlice> liststatus = client.get_range_slices(parent, predicate, keyrange, common.Constants.CL);
liststatus = Sort(liststatus);
result = ParseToJSON(liststatus);
} catch (InvalidRequestException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
private List<KeySlice> Sort(List<KeySlice> list) throws UnsupportedEncodingException
{
for (int i=0; i<list.size()-1; i++)
for (int j=i+1; j<list.size(); j++)
{
if (OutstandingPoint(list.get(i)) < OutstandingPoint(list.get(j)))
{
KeySlice temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
List<KeySlice> result = list.subList(0, 19);
return result;
}
//Tính điểm nổi bật của từng status like * 8 + dislike * 2
private int OutstandingPoint(KeySlice x) throws UnsupportedEncodingException
{
int like = 0,dislike = 0;
for (ColumnOrSuperColumn columnOrSuperColumn : x.getColumns()) {
if(columnOrSuperColumn.column.name == common.GeneralHandling.toByteBuffer(Status.colname_likecount))
like = Integer.parseInt(common.GeneralHandling.toString(columnOrSuperColumn.column.value));
if(columnOrSuperColumn.column.name == common.GeneralHandling.toByteBuffer(Status.colname_dislikecount))
dislike = Integer.parseInt(common.GeneralHandling.toString(columnOrSuperColumn.column.value));
}
return like * 8 + dislike * 2;
}
//Tăng số like lên 1
public boolean increaseLikecount(String status_ID)
{
boolean result = Inscrease(status_ID,Status.colname_likecount);
return result;
}
//Tăng số dislike lên 1
public boolean increaseDislikecount(String status_ID)
{
boolean result = Inscrease(status_ID,Status.colname_dislikecount);
return result;
}
private boolean Inscrease(String status_ID,String typecol)
{
boolean result = false;
try {
ByteBuffer id = common.GeneralHandling.toByteBuffer(status_ID);
ColumnParent parent = new ColumnParent(Status.col_parent);
ColumnPath path = new ColumnPath(Status.col_parent);
path.column = common.GeneralHandling.toByteBuffer(typecol);
ColumnOrSuperColumn status = client.get(id, path, common.Constants.CL);
int likecount_curr = Integer.parseInt(common.GeneralHandling.toString(status.column.value));
Column newcol = common.GeneralHandling.createCol(typecol, Integer.toString(likecount_curr + 1));
client.insert(id, parent, newcol, common.Constants.CL);
result = true;
} catch (NotFoundException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidRequestException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public String ParseToJSON(List<KeySlice> list)
{
String result = "{\"result\":[";
for (KeySlice keySlice : list) {
if (keySlice.columns.size() < 2)
continue;
try {
result += "{\"status_ID\":\"" + common.GeneralHandling.toString(keySlice.key) + "\"";
for (ColumnOrSuperColumn col : keySlice.columns) {
Column c = col.column;
String colname = common.GeneralHandling.toString(c.name);
if (colname.equals(Status.colname_content))
result += ",\"" + Status.colname_content + "\":\"" + common.GeneralHandling.toString(c.value) + "\"";
else if(colname.equals(Status.colname_tags))
result += ",\"" + Status.colname_tags + "\":\"" + common.GeneralHandling.toString(c.value) + "\"},";
}
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(StatusDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
int x = result.length();
result = result.substring(0, x - 1);
result += "]}";
return result;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import common.GeneralHandling;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.cassandra.thrift.*;
import org.apache.thrift.TException;
import pojo.Tag;
/**
*
* @author tipuder
*/
public class TagDAO {
private static Cassandra.Client client;
private static TagDAO instance;
public static TagDAO getInstance(Cassandra.Client _client)
{
if (instance != null)
return instance;
instance = new TagDAO();
client = _client;
return instance;
}
public boolean InsertTag(Tag newTag)
{
boolean result = false;
try {
//Tạo supercolumn list_status_ID
// SuperColumn liststatus = new SuperColumn();
// liststatus.name = common.GeneralHandling.toByteBuffer(Tag.name_scol_lstatus);
// List<String> lstatus = newTag.getList_status_ID();
// for (int i = 0; i < newTag.getList_status_ID().size(); i++)
// {
// String colname = lstatus.get(i);
// liststatus.addToColumns(common.GeneralHandling.createCol(colname, ""));
// }
//Tạo supercolumn info_tag
SuperColumn info_tag = new SuperColumn();
info_tag.name = common.GeneralHandling.toByteBuffer(Tag.name_scol_info);
//String createD = Long.toString((new Date()).getTime());
info_tag.addToColumns(common.GeneralHandling.createCol(Tag.name_col_cdate, ""));
String modifyD = "";
info_tag.addToColumns(common.GeneralHandling.createCol(Tag.name_col_mdate, modifyD));
String state = "public";
info_tag.addToColumns(common.GeneralHandling.createCol(Tag.name_col_state, state));
//Insert supercolunm bằng batch_mutate
ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(newTag.getName_tag());
List<Mutation> mutations = new ArrayList<Mutation>();
ColumnOrSuperColumn colorsupcol = new ColumnOrSuperColumn();
Mutation m = new Mutation();
colorsupcol.setSuper_column(info_tag);
m.setColumn_or_supercolumn(colorsupcol);
mutations.add(m);
// colorsupcol = new ColumnOrSuperColumn();
// m = new Mutation();
// colorsupcol.setSuper_column(liststatus);
// m.setColumn_or_supercolumn(colorsupcol);
// mutations.add(m);
Map<String, List<Mutation>> keyMutations = new HashMap<String, List<Mutation>>();
keyMutations.put(Tag.col_parent, mutations);
Map<ByteBuffer, Map<String, List<Mutation>>> mutationsMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
mutationsMap.put(rowkey, keyMutations);
client.batch_mutate(mutationsMap, common.Constants.CL);
result = true;
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidRequestException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public boolean InsertStatusIDtoTag(String StatusID,String nameTag)
{
boolean result = false;
try {
Tag updateTag = selectTagFromID(nameTag);
SuperColumn liststatus = new SuperColumn();
liststatus.name = common.GeneralHandling.toByteBuffer(Tag.name_scol_lstatus);
List<String> lstatus = updateTag.getList_status_ID();
if (lstatus == null)
lstatus = new ArrayList<String>();
lstatus.add(StatusID);
for (int i = 0; i < lstatus.size(); i++)
{
String colname = lstatus.get(i);
liststatus.addToColumns(common.GeneralHandling.createCol(colname, ""));
}
ByteBuffer rowkey = common.GeneralHandling.toByteBuffer(updateTag.getName_tag());
List<Mutation> mutations = new ArrayList<Mutation>();
ColumnOrSuperColumn colorsupcol = new ColumnOrSuperColumn();
Mutation m = new Mutation();
colorsupcol.setSuper_column(liststatus);
m.setColumn_or_supercolumn(colorsupcol);
mutations.add(m);
Map<String, List<Mutation>> keyMutations = new HashMap<String, List<Mutation>>();
keyMutations.put(Tag.col_parent, mutations);
Map<ByteBuffer, Map<String, List<Mutation>>> mutationsMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
mutationsMap.put(rowkey, keyMutations);
client.batch_mutate(mutationsMap, common.Constants.CL);
result = true;
} catch (InvalidRequestException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public Tag selectTagFromID(String nameTag)
{
Tag result = new Tag();
try {
SlicePredicate predicate = new SlicePredicate();
SliceRange range = new SliceRange(GeneralHandling.toByteBuffer(""), GeneralHandling.toByteBuffer(""), false, 10);
predicate.setSlice_range(range);
ColumnParent parent = new ColumnParent(Tag.col_parent);
List<ColumnOrSuperColumn> results = client.get_slice(GeneralHandling.toByteBuffer(nameTag), parent, predicate, common.Constants.CL);
if (!results.isEmpty())
{
result.setName_tag(nameTag);
for (ColumnOrSuperColumn temp : results)
{
SuperColumn sc = temp.super_column;
String colname = common.GeneralHandling.toString(sc.name);
if (Tag.name_scol_lstatus.equals(colname))
{
List<String> list_status_ID = new ArrayList<String>();
for (Column col : sc.columns)
list_status_ID.add(common.GeneralHandling.toString(col.name));
result.setList_status_ID(list_status_ID);
}
else
for (Column col : sc.columns)
{
String name = common.GeneralHandling.toString(col.name);
switch (name.charAt(0))
{
case 'c':
{
result.setCreate_date(common.GeneralHandling.toString(col.value));
}
case 'm':
{
result.setModify_date(common.GeneralHandling.toString(col.value));
}
case 's':
{
result.setState("public");
}
}
}
}
}
} catch (TException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidRequestException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public boolean RemoveTag(String rowkey)
{
boolean result = false;
try {
long time = System.currentTimeMillis();
ColumnPath path = new ColumnPath();
path.column_family = Tag.col_parent;
path.super_column = common.GeneralHandling.toByteBuffer(Tag.name_scol_info);
client.remove(common.GeneralHandling.toByteBuffer(rowkey),path,time,common.Constants.CL);
path = new ColumnPath();
path.column_family = Tag.col_parent;
path.super_column = common.GeneralHandling.toByteBuffer(Tag.name_scol_lstatus);
client.remove(common.GeneralHandling.toByteBuffer(rowkey),path,time,common.Constants.CL);
result = true;
} catch (InvalidRequestException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
public void PrintALLTag()
{
try {
List<ByteBuffer> colNames = new ArrayList<ByteBuffer>();
colNames.add(common.GeneralHandling.toByteBuffer(Tag.name_scol_info));
SlicePredicate predicate = new SlicePredicate();
predicate.column_names = colNames;
ColumnParent parent = new ColumnParent(Tag.col_parent);
KeyRange range = new KeyRange();
range.start_key = common.GeneralHandling.toByteBuffer("s");
range.end_key = common.GeneralHandling.toByteBuffer("");
List<KeySlice> results = client.get_range_slices(parent, predicate, range, common.Constants.CL);
for (KeySlice row : results)
{
Tag temp = selectTagFromID(common.GeneralHandling.toString(row.key));
if (temp.getName_tag() != null)
PrintTag(temp);
}
} catch (TException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidRequestException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void PrintTag(Tag temp)
{
System.out.println("Key : " + temp.getName_tag());
System.out.println("List status ID : ");
List<String> list = temp.getList_status_ID();
for (int i = 0; i < list.size(); i++)
{
String x = list.get(i) + ", ";
System.out.print(x);
}
System.out.println();
System.out.println("Create Date : " + temp.getCreate_date());
System.out.println("Modify Date : " + temp.getModify_date());
System.out.println("State : " + temp.getState());
System.out.println("-----------------------------------------");
}
public String PrintALLTag_S()
{
String result = "{\"result\":[";
try {
List<ByteBuffer> colNames = new ArrayList<ByteBuffer>();
colNames.add(common.GeneralHandling.toByteBuffer(Tag.name_scol_info));
SlicePredicate predicate = new SlicePredicate();
predicate.column_names = colNames;
ColumnParent parent = new ColumnParent(Tag.col_parent);
KeyRange range = new KeyRange();
range.start_key = common.GeneralHandling.toByteBuffer("");
range.end_key = common.GeneralHandling.toByteBuffer("");
List<KeySlice> results = client.get_range_slices(parent, predicate, range, common.Constants.CL);
for (KeySlice row : results)
{
Tag temp = selectTagFromID(common.GeneralHandling.toString(row.key));
if (temp.getName_tag() != null && temp.getList_status_ID() != null)
result += PrintTag_S(temp);
}
result = result.substring(0, result.length()-1);
result += "]}";
} catch (TException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidRequestException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnavailableException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (TimedOutException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(TagDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
private String PrintTag_S(Tag temp)
{
String result = "";
result += "{\"Key\":\"" + temp.getName_tag() + "\",";
result += "\"List status ID\":\"";
List<String> list = temp.getList_status_ID();
for (int i = 0; i < list.size(); i++)
{
String x = list.get(i) + ",";
result += x;
}
result = result.substring(0, result.length()-1);
result += "\",";
result += "\"Create Date\":\"" + temp.getCreate_date() + "\",";
result += "\"Modify Date\":\"" + temp.getModify_date() + "\",";
result += "\"State\":\"" + temp.getState() + "\"},";
return result;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ServicesAccessData;
/**
*
* @author tipuder
*/
public class Server {
}
| Java |
package Testing;
import DAO.TagDAO;
import DAO.UserDAO;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
public class app
{
public static void main(String[] args)
{
try {
TTransport tr = new TFramedTransport(new TSocket(common.Constants.HOST, common.Constants.PORT));
TProtocol proto = new TBinaryProtocol(tr);
Cassandra.Client client = new Cassandra.Client(proto);
tr.open();
client.set_keyspace(common.Constants.KEYSPACE);
TagDAO Tag_DAO = TagDAO.getInstance(client);
// String[] listname = {"chúc tết","tiền","break up","châm biếm",
// "châm ngôn sống","cuộc sống","failure",
// "gia đình","heart","hài hước","hôn nhân",
// "life","love","lời hay ý đẹp","mới nhất",
// "phụ nữ","thành công","tình bạn","tình cảm",
// "tình yêu","vui vẻ","đàn ông"};
// for (int j=0; j<listname.length;j++)
// {
// Tag newTag = new Tag();
//
//// List<String> liststatusID = new ArrayList<String>();
//// Random rd = new Random();
//// for (int i = 0; i < rd.nextInt(4) + 3; i++)
//// liststatusID.add(Integer.toString(rd.nextInt(20)+2));
// newTag.setName_tag(listname[j]);
// //newTag.setList_status_ID(liststatusID);
//
// if (tag_DAO.InsertTag(newTag))
// System.out.println("Insert thành công");
// }
//// if (tag_DAO.RemoveTag("Tình yêu"));
//// System.out.println("Remove thành công");
// StatusDAO sta_DAO = StatusDAO.getInstance(client);
// Status newstatus = new Status();
// newstatus.setContent("Người ta có thể quên đi điều bạn nói, nhưng những gì bạn để lại trong lòng họ thì không bao giờ nhạt phai." );
// newstatus.setTags("tình bạn");
// Random rd = new Random();
//
// newstatus.setLike_count(Integer.toString(rd.nextInt(30)));
// newstatus.setDislike_count(Integer.toString(rd.nextInt(30)));
// if (sta_DAO.InsertStatus(newstatus))
// System.out.println("Insert thành công");
//
TagDAO user_DAO = TagDAO.getInstance(client);
String result = user_DAO.PrintALLTag_S();
System.out.println(result);
tr.close();
} catch (InvalidRequestException ex) {
Logger.getLogger(app.class.getName()).log(Level.SEVERE, null, ex);
} catch (TException ex) {
Logger.getLogger(app.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author mvaleev
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jLabel1.setText("Диапазон сети");
jButton1.setText("Сканировать");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Очистить");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Сохранить");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jLabel2.setText(" ");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)))
.addGap(31, 31, 31))
.addGroup(layout.createSequentialGroup()
.addGap(103, 103, 103)
.addComponent(jButton2)
.addGap(55, 55, 55)
.addComponent(jButton3)
.addContainerGap(100, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(4, 4, 4)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton3))
.addGap(25, 25, 25))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String ipAddrRaw = jTextField1.getText();
String ipAddr[] = ipAddrRaw.split("/");
jTextField1.setText(null);
jTextArea1.append(ipAddr[0] + " ip " + ipAddr[1] + " mmmask\n");
/* try {
InetAddress inet = InetAddress.getByName(ipAddr[0]);
boolean status = inet.isReachable(5000);
if (status) {
jTextArea1.append(ipAddr[0] + " в сети\n");
}
else {
jTextArea1.append(ipAddr[0] + " не в сети\n");
}
}
catch (UnknownHostException e) {
jTextArea1.append(ipAddr[0] + " не правильно задан диапазон\n");
}
catch (IOException e) {
jTextArea1.append(ipAddr[0] + " ошибка\n");
}*/
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
jTextArea1.setText(null);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt", "txt");
chooser.setFileFilter(filter);
if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File f = new File(chooser.getSelectedFile().getAbsolutePath());
try {
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(jTextArea1.getText());
bw.close();
fw.close();
/*if (f.exists()) {
if (JOptionPane.showConfirmDialog(chooser, "Owerwrite?") == JOptionPane.YES_OPTION) {
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(jTextArea1.getText());
bw.close();
fw.close();
}
}*/
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_jButton3ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
| Java |
package net.coobird.thumbnailator;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import net.coobird.thumbnailator.filters.ImageFilter;
import net.coobird.thumbnailator.resizers.FixedResizerFactory;
import net.coobird.thumbnailator.geometry.Region;
import net.coobird.thumbnailator.resizers.Resizer;
import net.coobird.thumbnailator.resizers.ResizerFactory;
/**
* This class is used to specify the parameters to use when creating a thumbnail.
* <p>
* An instance of {@link ThumbnailParameter} is mutable -- it should not be
* reused for multiple resizes, as the parameters can change behind the scenes
* as the resizing process progresses.
*
* @author coobird
*
*/
public class ThumbnailParameter
{
/**
* A constant used to denote that the output format of the thumbnail should
* be the same as the format of the original image.
*/
public static final String ORIGINAL_FORMAT = null;
/**
* A constant used to denote that the output format of the thumbnail should
* be the determined from available information such as the file name of
* the thumbnail.
* <p>
* If a suitable output format cannot be determined, then the implementation
* should behave as if {@link #ORIGINAL_FORMAT} was specified.
*/
public static final String DETERMINE_FORMAT = "\0";
/**
* A constant used to denote that the output format type of the thumbnail
* should be the default type of the codec being used.
*/
public static final String DEFAULT_FORMAT_TYPE = null;
/**
* A constant used to denote that the default compression quality settings
* should be used when creating the thumbnail.
*/
public static final float DEFAULT_QUALITY = Float.NaN;
/**
* A constant used to denote that the image type of the original image
* should be used when creating the thumbnail.
*/
public static final int ORIGINAL_IMAGE_TYPE = -1;
/**
* A constant used to denote that the default image type should be used
* when creating the thumbnail.
*/
public static final int DEFAULT_IMAGE_TYPE = BufferedImage.TYPE_INT_ARGB;
/**
* The thumbnail size.
* <p>
* If this field is set, then the {@link #scalingFactor} field will be set
* as {@link Double#NaN} to indicate that it is not set.
*/
private final Dimension thumbnailSize;
/**
* The scaling factor to apply to the width when creating a thumbnail from
* the original image.
* <p>
* If this field is set, then the {@link #thumbnailSize} field will be set
* as {@code null} to indicate that it is not set.
*/
private final double widthScalingFactor;
/**
* The scaling factor to apply to the height when creating a thumbnail from
* the original image.
* <p>
* If this field is set, then the {@link #thumbnailSize} field will be set
* as {@code null} to indicate that it is not set.
*/
private final double heightScalingFactor;
/**
* Indicated whether or not the thumbnail should retain the aspect ratio
* the same as the original image when the aspect ratio of the desired
* dimensions for the thumbnail does not match the ratio of the original
* image.
*/
private final boolean keepAspectRatio;
/**
* The output format for the thumbnail.
* <p>
* A value of {@link ThumbnailParameter#ORIGINAL_FORMAT} indicates that the
* image format of the original image should be used as the output format.
* <p>
* A value of {@link ThumbnailParameter#DETERMINE_FORMAT} indicates that the
* output format of the thumbnail should be the determined from the
* information available, such as the output file name of the thumbnail.
*/
private final String outputFormat;
/**
* The output format type for the thumbnail.
* <p>
* A value of {@link ThumbnailParameter#DEFAULT_FORMAT_TYPE} indicates
* that the default type of the specified compression format should be used
* as the output format type.
*/
private final String outputFormatType;
/**
* The output quality settings which will be used by the image compressor.
* <p>
* An acceptable value is in the range of {@code 0.0f} to {@code 1.0f},
* where {@code 0.0f} is for the lowest quality setting and {@code 1.0f} for
* the highest quality setting.
* <p>
* A value of {@link Float#NaN} indicates that the default quality settings
* of the output codec should be used.
*/
private final float outputQuality;
/**
* The image type of the {@code BufferedImage} used for the thumbnail.
*/
private final int imageType;
/**
* {@link ImageFilter}s to apply to the thumbnail.
* <p>
* The filters will be applied after the original image has been resized.
*/
private final List<ImageFilter> filters;
/**
* The {@link ResizerFactory} for obtaining a {@link Resizer} that is
* to be used when performing an image resizing operation.
*/
private final ResizerFactory resizerFactory;
/**
* The region of the source image to use when creating a thumbnail.
* <p>
* A value of {@code null} represents that the entire source image should
* be used to create the thumbnail.
*/
private final Region sourceRegion;
/**
* Whether or not to fit the thumbnail within the specified dimensions.
* <p>
* If {@code true} is specified, then the thumbnail will be sized to fit
* within the specified dimensions, if the thumbnail is going to exceed
* those dimensions.
*/
private final boolean fitWithinDimensions;
/**
* Whether or not to use the Exif orientation metadata to orient the
* thumbnails.
*/
private final boolean useExifOrientation;
/**
* Private constructor which sets all the required fields, and performs
* validation of the given arguments.
* <p>
* This constructor is to be called from all the public constructors.
*
* @param thumbnailSize The size of the thumbnail to generate.
* @param widthScalingFactor The scaling factor to apply to the width
* when creating a thumbnail from the original
* image.
* @param heightScalingFactor The scaling factor to apply to the height
* when creating a thumbnail from the original
* image.
* @param sourceRegion The region of the source image to use when
* creating a thumbnail.
* A value of {@code null} indicates that the
* entire source image should be used to create
* the thumbnail.
* @param keepAspectRatio Indicates whether or not the thumbnail should
* maintain the aspect ratio of the original image.
* @param outputFormat A string indicating the compression format
* that should be applied on the thumbnail.
* A value of
* {@link ThumbnailParameter#ORIGINAL_FORMAT}
* should be provided if the same image format as
* the original should be used for the thumbnail.
* A value of
* {@link ThumbnailParameter#DETERMINE_FORMAT}
* should be provided if the output format of the
* thumbnail should be the determined from the
* information available, such as the output file
* name of the thumbnail.
* @param outputFormatType A string indicating the compression type that
* should be used when writing the thumbnail.
* A value of
* {@link ThumbnailParameter#DEFAULT_FORMAT_TYPE}
* should be provided if the thumbnail should be
* written using the default compression type of
* the codec specified in {@code outputFormat}.
* @param outputQuality A value from {@code 0.0f} to {@code 1.0f} which
* indicates the quality setting to use for the
* compression of the thumbnail. {@code 0.0f}
* indicates the lowest quality, {@code 1.0f}
* indicates the highest quality setting for the
* compression.
* {@link ThumbnailParameter#DEFAULT_QUALITY}
* should be specified when the codec's default
* compression quality settings should be used.
* @param imageType The {@link BufferedImage} image type of the
* thumbnail.
* A value of
* {@link ThumbnailParameter#DEFAULT_IMAGE_TYPE}
* should be specified when the default image
* type should be used when creating the thumbnail.
* @param filters The {@link ImageFilter}s to apply to the
* thumbnail.
* A value of {@code null} will be recognized as
* no filters are to be applied.
* The filters are applied after the original
* image has been resized.
* @param resizerFactory The {@link ResizerFactory} for obtaining a
* {@link Resizer} that is to be used when
* performing an image resizing operation.
* @param fitWithinDimensions Whether or not to fit the thumbnail within
* the specified dimensions.
* <p>
* If {@code true} is specified, then the
* thumbnail will be sized to fit within the
* specified dimensions, if the thumbnail is
* going to exceed those dimensions.
* @param useExifOrientation Whether or not to use the Exif metadata to
* determine the orientation of the thumbnail.
* <p>
* If {@code true} is specified, then the
* Exif metadata will be used to determine
* the orientation of the thumbnail.
*
* @throws IllegalArgumentException If the scaling factor is not a
* rational number or is less than or
* equal to 0, or if the
* {@link ResizerFactory} is null.
*/
private ThumbnailParameter(
Dimension thumbnailSize,
double widthScalingFactor,
double heightScalingFactor,
Region sourceRegion,
boolean keepAspectRatio,
String outputFormat,
String outputFormatType,
float outputQuality,
int imageType,
List<ImageFilter> filters,
ResizerFactory resizerFactory,
boolean fitWithinDimensions,
boolean useExifOrientation
)
{
// The following 2 fields are set by the public constructors.
this.thumbnailSize = thumbnailSize;
this.widthScalingFactor = widthScalingFactor;
this.heightScalingFactor = heightScalingFactor;
this.keepAspectRatio = keepAspectRatio;
this.sourceRegion = sourceRegion;
this.outputFormat = outputFormat;
this.outputFormatType = outputFormatType;
/*
* Note:
* The value of DEFAULT_QUALITY is Float.NaN which cannot be compared
* by using the regular == operator. Therefore, to check that NaN is
* being used, one must use the Float.NaN method.
*/
if ( (outputQuality < 0.0f || outputQuality > 1.0f) &&
!Float.isNaN(outputQuality) )
{
throw new IllegalArgumentException("The output quality must be " +
"between 0.0f and 1.0f, or Float.NaN to use the default " +
"compression quality of codec being used.");
}
this.outputQuality = outputQuality;
this.imageType = imageType;
// Creating a new ArrayList, as `filters` should be mutable as of 0.4.3.
if (filters == null)
{
this.filters = new ArrayList<ImageFilter>();
}
else
{
this.filters = new ArrayList<ImageFilter>(filters);
}
if (resizerFactory == null)
{
throw new IllegalArgumentException("Resizer cannot be null");
}
this.resizerFactory = resizerFactory;
this.fitWithinDimensions = fitWithinDimensions;
this.useExifOrientation = useExifOrientation;
}
/**
* Perform validations on the {@code thumbnailSize} field.
*/
private void validateThumbnailSize()
{
if (thumbnailSize == null)
{
throw new IllegalArgumentException("Thumbnail size cannot be null.");
}
else if (thumbnailSize.width < 0 || thumbnailSize.height < 0)
{
throw new IllegalArgumentException("Thumbnail dimensions must be greater than 0.");
}
}
/**
* Perform validations on the {@code scalingFactor} field.
*/
private void validateScalingFactor()
{
if (widthScalingFactor <= 0.0 || heightScalingFactor <= 0.0)
{
throw new IllegalArgumentException("Scaling factor is less than or equal to 0.");
}
else if (Double.isNaN(widthScalingFactor) || Double.isInfinite(widthScalingFactor))
{
throw new IllegalArgumentException("Scaling factor must be a rational number.");
}
else if (Double.isNaN(heightScalingFactor) || Double.isInfinite(heightScalingFactor))
{
throw new IllegalArgumentException("Scaling factor must be a rational number.");
}
}
/**
* Creates an object holding the parameters needed in order to make a
* thumbnail.
*
* @param thumbnailSize The size of the thumbnail to generate.
* @param sourceRegion The region of the source image to use when
* creating a thumbnail.
* A value of {@code null} indicates that the
* entire source image should be used to create
* the thumbnail.
* @param keepAspectRatio Indicates whether or not the thumbnail should
* maintain the aspect ratio of the original image.
* @param outputFormat A string indicating the compression format
* that should be applied on the thumbnail.
* A value of
* {@link ThumbnailParameter#ORIGINAL_FORMAT}
* should be provided if the same image format as
* the original should be used for the thumbnail.
* A value of
* {@link ThumbnailParameter#DETERMINE_FORMAT}
* should be provided if the output format of the
* thumbnail should be the determined from the
* information available, such as the output file
* name of the thumbnail.
* @param outputFormatType A string indicating the compression type that
* should be used when writing the thumbnail.
* A value of
* {@link ThumbnailParameter#DEFAULT_FORMAT_TYPE}
* should be provided if the thumbnail should be
* written using the default compression type of
* the codec specified in {@code outputFormat}.
* @param outputQuality A value from {@code 0.0f} to {@code 1.0f} which
* indicates the quality setting to use for the
* compression of the thumbnail. {@code 0.0f}
* indicates the lowest quality, {@code 1.0f}
* indicates the highest quality setting for the
* compression.
* {@link ThumbnailParameter#DEFAULT_QUALITY}
* should be specified when the codec's default
* compression quality settings should be used.
* @param imageType The {@link BufferedImage} image type of the
* thumbnail.
* A value of
* {@link ThumbnailParameter#DEFAULT_IMAGE_TYPE}
* should be specified when the default image
* type should be used when creating the thumbnail.
* @param filters The {@link ImageFilter}s to apply to the
* thumbnail.
* A value of {@code null} will be recognized as
* no filters are to be applied.
* The filters are applied after the original
* image has been resized.
* @param resizer The {@link Resizer} to use when performing the
* resizing operation to create a thumbnail.
* @param fitWithinDimensions Whether or not to fit the thumbnail within
* the specified dimensions.
* <p>
* If {@code true} is specified, then the
* thumbnail will be sized to fit within the
* specified dimensions, if the thumbnail is
* going to exceed those dimensions.
* @param useExifOrientation Whether or not to use the Exif metadata to
* determine the orientation of the thumbnail.
* <p>
* If {@code true} is specified, then the
* Exif metadata will be used to determine
* the orientation of the thumbnail.
*
* @throws IllegalArgumentException If size is {@code null} or if the
* dimensions are negative, or if the
* {@link Resizer} is null.
* @since 0.4.3
*/
public ThumbnailParameter(
Dimension thumbnailSize,
Region sourceRegion,
boolean keepAspectRatio,
String outputFormat,
String outputFormatType,
float outputQuality,
int imageType,
List<ImageFilter> filters,
Resizer resizer,
boolean fitWithinDimensions,
boolean useExifOrientation
)
{
this(
thumbnailSize,
Double.NaN,
Double.NaN,
sourceRegion,
keepAspectRatio,
outputFormat,
outputFormatType,
outputQuality,
imageType,
filters,
new FixedResizerFactory(resizer),
fitWithinDimensions,
useExifOrientation
);
validateThumbnailSize();
}
/**
* Creates an object holding the parameters needed in order to make a
* thumbnail.
*
* @param widthScalingFactor The scaling factor to apply to the width
* when creating a thumbnail from the original
* image.
* @param heightScalingFactor The scaling factor to apply to the height
* when creating a thumbnail from the original
* image.
* @param sourceRegion The region of the source image to use when
* creating a thumbnail.
* A value of {@code null} indicates that the
* entire source image should be used to create
* the thumbnail.
* @param keepAspectRatio Indicates whether or not the thumbnail should
* maintain the aspect ratio of the original image.
* @param outputFormat A string indicating the compression format
* that should be applied on the thumbnail.
* A value of
* {@link ThumbnailParameter#ORIGINAL_FORMAT}
* should be provided if the same image format as
* the original should be used for the thumbnail.
* A value of
* {@link ThumbnailParameter#DETERMINE_FORMAT}
* should be provided if the output format of the
* thumbnail should be the determined from the
* information available, such as the output file
* name of the thumbnail.
* @param outputFormatType A string indicating the compression type that
* should be used when writing the thumbnail.
* A value of
* {@link ThumbnailParameter#DEFAULT_FORMAT_TYPE}
* should be provided if the thumbnail should be
* written using the default compression type of
* the codec specified in {@code outputFormat}.
* @param outputQuality A value from {@code 0.0f} to {@code 1.0f} which
* indicates the quality setting to use for the
* compression of the thumbnail. {@code 0.0f}
* indicates the lowest quality, {@code 1.0f}
* indicates the highest quality setting for the
* compression.
* {@link ThumbnailParameter#DEFAULT_QUALITY}
* should be specified when the codec's default
* compression quality settings should be used.
* @param imageType The {@link BufferedImage} image type of the
* thumbnail.
* A value of
* {@link ThumbnailParameter#DEFAULT_IMAGE_TYPE}
* should be specified when the default image
* type should be used when creating the thumbnail.
* @param filters The {@link ImageFilter}s to apply to the
* thumbnail.
* A value of {@code null} will be recognized as
* no filters are to be applied.
* The filters are applied after the original
* image has been resized.
* @param resizer The {@link Resizer} to use when performing the
* resizing operation to create a thumbnail.
* @param fitWithinDimensions Whether or not to fit the thumbnail within
* the specified dimensions.
* <p>
* If {@code true} is specified, then the
* thumbnail will be sized to fit within the
* specified dimensions, if the thumbnail is
* going to exceed those dimensions.
* @param useExifOrientation Whether or not to use the Exif metadata to
* determine the orientation of the thumbnail.
* <p>
* If {@code true} is specified, then the
* Exif metadata will be used to determine
* the orientation of the thumbnail.
*
* @throws IllegalArgumentException If the scaling factor is not a
* rational number or is less than or
* equal to 0, or if the
* {@link Resizer} is null.
* @since 0.4.3
*/
public ThumbnailParameter(
double widthScalingFactor,
double heightScalingFactor,
Region sourceRegion,
boolean keepAspectRatio,
String outputFormat,
String outputFormatType,
float outputQuality,
int imageType,
List<ImageFilter> filters,
Resizer resizer,
boolean fitWithinDimensions,
boolean useExifOrientation
)
{
this(
null,
widthScalingFactor,
heightScalingFactor,
sourceRegion,
keepAspectRatio,
outputFormat,
outputFormatType,
outputQuality,
imageType,
filters,
new FixedResizerFactory(resizer),
fitWithinDimensions,
useExifOrientation
);
validateScalingFactor();
}
/**
* Creates an object holding the parameters needed in order to make a
* thumbnail.
*
* @param thumbnailSize The size of the thumbnail to generate.
* @param sourceRegion The region of the source image to use when
* creating a thumbnail.
* A value of {@code null} indicates that the
* entire source image should be used to create
* the thumbnail.
* @param keepAspectRatio Indicates whether or not the thumbnail should
* maintain the aspect ratio of the original image.
* @param outputFormat A string indicating the compression format
* that should be applied on the thumbnail.
* A value of
* {@link ThumbnailParameter#ORIGINAL_FORMAT}
* should be provided if the same image format as
* the original should be used for the thumbnail.
* A value of
* {@link ThumbnailParameter#DETERMINE_FORMAT}
* should be provided if the output format of the
* thumbnail should be the determined from the
* information available, such as the output file
* name of the thumbnail.
* @param outputFormatType A string indicating the compression type that
* should be used when writing the thumbnail.
* A value of
* {@link ThumbnailParameter#DEFAULT_FORMAT_TYPE}
* should be provided if the thumbnail should be
* written using the default compression type of
* the codec specified in {@code outputFormat}.
* @param outputQuality A value from {@code 0.0f} to {@code 1.0f} which
* indicates the quality setting to use for the
* compression of the thumbnail. {@code 0.0f}
* indicates the lowest quality, {@code 1.0f}
* indicates the highest quality setting for the
* compression.
* {@link ThumbnailParameter#DEFAULT_QUALITY}
* should be specified when the codec's default
* compression quality settings should be used.
* @param imageType The {@link BufferedImage} image type of the
* thumbnail.
* A value of
* {@link ThumbnailParameter#DEFAULT_IMAGE_TYPE}
* should be specified when the default image
* type should be used when creating the thumbnail.
* @param filters The {@link ImageFilter}s to apply to the
* thumbnail.
* A value of {@code null} will be recognized as
* no filters are to be applied.
* The filters are applied after the original
* image has been resized.
* @param resizerFactory The {@link ResizerFactory} for obtaining a
* {@link Resizer} that is to be used when
* performing an image resizing operation.
* @param fitWithinDimensions Whether or not to fit the thumbnail within
* the specified dimensions.
* <p>
* If {@code true} is specified, then the
* thumbnail will be sized to fit within the
* specified dimensions, if the thumbnail is
* going to exceed those dimensions.
* @param useExifOrientation Whether or not to use the Exif metadata to
* determine the orientation of the thumbnail.
* <p>
* If {@code true} is specified, then the
* Exif metadata will be used to determine
* the orientation of the thumbnail.
*
* @throws IllegalArgumentException If size is {@code null} or if the
* dimensions are negative, or if the
* {@link ResizerFactory} is null.
* @since 0.4.3
*/
public ThumbnailParameter(
Dimension thumbnailSize,
Region sourceRegion,
boolean keepAspectRatio,
String outputFormat,
String outputFormatType,
float outputQuality,
int imageType,
List<ImageFilter> filters,
ResizerFactory resizerFactory,
boolean fitWithinDimensions,
boolean useExifOrientation
)
{
this(
thumbnailSize,
Double.NaN,
Double.NaN,
sourceRegion,
keepAspectRatio,
outputFormat,
outputFormatType,
outputQuality,
imageType,
filters,
resizerFactory,
fitWithinDimensions,
useExifOrientation
);
validateThumbnailSize();
}
/**
* Creates an object holding the parameters needed in order to make a
* thumbnail.
*
* @param widthScalingFactor The scaling factor to apply to the width
* when creating a thumbnail from the original
* image.
* @param heightScalingFactor The scaling factor to apply to the height
* when creating a thumbnail from the original
* image.
* @param sourceRegion The region of the source image to use when
* creating a thumbnail.
* A value of {@code null} indicates that the
* entire source image should be used to create
* the thumbnail.
* @param keepAspectRatio Indicates whether or not the thumbnail should
* maintain the aspect ratio of the original image.
* @param outputFormat A string indicating the compression format
* that should be applied on the thumbnail.
* A value of
* {@link ThumbnailParameter#ORIGINAL_FORMAT}
* should be provided if the same image format as
* the original should be used for the thumbnail.
* A value of
* {@link ThumbnailParameter#DETERMINE_FORMAT}
* should be provided if the output format of the
* thumbnail should be the determined from the
* information available, such as the output file
* name of the thumbnail.
* @param outputFormatType A string indicating the compression type that
* should be used when writing the thumbnail.
* A value of
* {@link ThumbnailParameter#DEFAULT_FORMAT_TYPE}
* should be provided if the thumbnail should be
* written using the default compression type of
* the codec specified in {@code outputFormat}.
* @param outputQuality A value from {@code 0.0f} to {@code 1.0f} which
* indicates the quality setting to use for the
* compression of the thumbnail. {@code 0.0f}
* indicates the lowest quality, {@code 1.0f}
* indicates the highest quality setting for the
* compression.
* {@link ThumbnailParameter#DEFAULT_QUALITY}
* should be specified when the codec's default
* compression quality settings should be used.
* @param imageType The {@link BufferedImage} image type of the
* thumbnail.
* A value of
* {@link ThumbnailParameter#DEFAULT_IMAGE_TYPE}
* should be specified when the default image
* type should be used when creating the thumbnail.
* @param filters The {@link ImageFilter}s to apply to the
* thumbnail.
* A value of {@code null} will be recognized as
* no filters are to be applied.
* The filters are applied after the original
* image has been resized.
* @param resizerFactory The {@link ResizerFactory} for obtaining a
* {@link Resizer} that is to be used when
* performing an image resizing operation.
* @param fitWithinDimensions Whether or not to fit the thumbnail within
* the specified dimensions.
* <p>
* If {@code true} is specified, then the
* thumbnail will be sized to fit within the
* specified dimensions, if the thumbnail is
* going to exceed those dimensions.
* @param useExifOrientation Whether or not to use the Exif metadata to
* determine the orientation of the thumbnail.
* <p>
* If {@code true} is specified, then the
* Exif metadata will be used to determine
* the orientation of the thumbnail.
*
* @throws IllegalArgumentException If the scaling factor is not a
* rational number or is less than or
* equal to 0, or if the
* {@link ResizerFactory} is null.
* @since 0.4.3
*/
public ThumbnailParameter(
double widthScalingFactor,
double heightScalingFactor,
Region sourceRegion,
boolean keepAspectRatio,
String outputFormat,
String outputFormatType,
float outputQuality,
int imageType,
List<ImageFilter> filters,
ResizerFactory resizerFactory,
boolean fitWithinDimensions,
boolean useExifOrientation
)
{
this(
null,
widthScalingFactor,
heightScalingFactor,
sourceRegion,
keepAspectRatio,
outputFormat,
outputFormatType,
outputQuality,
imageType,
filters,
resizerFactory,
fitWithinDimensions,
useExifOrientation
);
validateScalingFactor();
}
/**
* Returns the size of the thumbnail.
* <p>
* Returns {@code null} if the scaling factor is set rather than the
* explicit thumbnail size.
*
* @return The size of the thumbnail.
*/
public Dimension getSize()
{
if (thumbnailSize != null)
{
return (Dimension)thumbnailSize.clone();
}
else
{
return null;
}
}
/**
* Returns the scaling factor to apply to the width when creating the
* thumbnail.
* <p>
* Returns {@link Double#NaN} if the thumbnail size is set rather than the
* scaling factor.
*
* @return The width scaling factor for the thumbnail.
* @since 0.3.10
*/
public double getWidthScalingFactor()
{
return widthScalingFactor;
}
/**
* Returns the scaling factor to apply to the height when creating the
* thumbnail.
* <p>
* Returns {@link Double#NaN} if the thumbnail size is set rather than the
* scaling factor.
*
* @return The height scaling factor for the thumbnail.
* @since 0.3.10
*/
public double getHeightScalingFactor()
{
return heightScalingFactor;
}
/**
* Returns the type of image. The value returned is the constant used for
* image types of {@link BufferedImage}.
*
* @return The type of the image.
*/
public int getType()
{
return imageType;
}
/**
* Returns whether or not the thumbnail is to maintain the aspect ratio of
* the source image when creating the thumbnail.
*
* @return {@code true} if the thumbnail is to maintain the aspect
* ratio of the original image, {@code false} otherwise.
*/
public boolean isKeepAspectRatio()
{
return keepAspectRatio;
}
/**
* Returns the output format for the thumbnail.
* <p>
* If the output format is to use the same compression format as the
* original image, this method will return
* {@link ThumbnailParameter#ORIGINAL_FORMAT}.
* <p>
* If the output format should be determined from the information available
* such as the file name of the thumbnail, then this method will return
* {@link ThumbnailParameter#DETERMINE_FORMAT}.
*
* @return The output format for the thumbnail.
*/
public String getOutputFormat()
{
return outputFormat;
}
/**
* Returns the output format type for the thumbnail.
* <p>
* If the default compression type of the compression format is to be used,
* then this method will return
* {@link ThumbnailParameter#DEFAULT_FORMAT_TYPE}.
*
* @return The output format type for the thumbnail.
*/
public String getOutputFormatType()
{
return outputFormatType;
}
/**
* Returns the compression quality settings for the thumbnail.
* <p>
* The value is in the range of {@code 0.0f} to {@code 1.0f},
* where {@code 0.0f} is for the lowest quality setting and {@code 1.0f} for
* the highest quality setting.
* <p>
* If the default compression quality is to be used, then this method will
* return {@link ThumbnailParameter#DEFAULT_QUALITY}.
*
* @return The compression quality settings for the thumbnail.
*/
public float getOutputQuality()
{
return outputQuality;
}
/**
* Returns the list of {@link ImageFilter}s which are applied to the
* thumbnail.
* <p>
* These filters are applied after the original image has been resized.
*
* @return The {@link ImageFilter}s which are applied to the thumbnail.
*/
public List<ImageFilter> getImageFilters()
{
return filters;
}
/**
* Returns the default {@link Resizer} that will be used when performing the
* resizing operation to create a thumbnail.
*
* @return The default {@link Resizer} to use when performing a resize
* operation.
*/
public Resizer getResizer()
{
return resizerFactory.getResizer();
}
/**
* Returns the {@link ResizerFactory} for obtaining a {@link Resizer} which
* is to be used when performing the resizing operation to create a
* thumbnail.
*
* @return The {@link ResizerFactory} to use to obtain the
* {@link Resizer}.
*/
public ResizerFactory getResizerFactory()
{
return resizerFactory;
}
/**
* Returns whether or not the original image type should be used for the
* thumbnail.
*
* @return {@code true} if the original image type should be used,
* {@code false} otherwise.
*/
public boolean useOriginalImageType()
{
return imageType == ORIGINAL_IMAGE_TYPE;
}
/**
* Returns the region of the source image to use when creating a thumbnail,
* represented by a {@link Region} object.
*
* @return The {@code Region} object representing the source region
* to use when creating a thumbnail.
* <p>
* A value of {@code null} indicates that the entire source
* image should be used to create the thumbnail.
*/
public Region getSourceRegion()
{
return sourceRegion;
}
/**
* Returns whether or not to fit the thumbnail within the specified
* dimensions.
*
* @return {@code true} is returned when the thumbnail should be sized
* to fit within the specified dimensions, if the thumbnail
* is going to exceed those dimensions.
* @since 0.4.0
*/
public boolean fitWithinDimenions()
{
return fitWithinDimensions;
}
/**
* Returns whether or not the Exif metadata should be used to determine
* the orientation of the thumbnail.
*
* @return {@code true} is returned when the Exif metadata should be
* used to decide the orientation of the thumbnail,
* {@code false} otherwise.
* @since 0.4.3
*/
public boolean useExifOrientation()
{
return useExifOrientation;
}
}
| Java |
package net.coobird.thumbnailator.makers;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import net.coobird.thumbnailator.builders.BufferedImageBuilder;
import net.coobird.thumbnailator.resizers.FixedResizerFactory;
import net.coobird.thumbnailator.resizers.Resizer;
import net.coobird.thumbnailator.resizers.DefaultResizerFactory;
import net.coobird.thumbnailator.resizers.ResizerFactory;
/**
* An abstract class which provides support functionalities for
* {@link ThumbnailMaker} implementations.
*
* @author coobird
*
*/
public abstract class ThumbnailMaker
{
/**
* String used for an exception message.
*/
private static final String NOT_READY_FOR_MAKE = "Maker not ready to " +
"make thumbnail.";
/**
* Used when determining whether the "imageType" parameter has been set
* already or not.
*/
private static final String PARAM_IMAGE_TYPE = "imageType";
/**
* Used when determining whether the "resizer" parameter has been set
* already or not.
*/
private static final String PARAM_RESIZER = "resizer";
/**
* Used when determining whether the "resizerFactory" parameter has been set
* already or not.
*/
private static final String PARAM_RESIZERFACTORY = "resizerFactory";
/**
* Class which keeps track of the parameters being set for the
* {@link ThumbnailMaker}.
* <p>
* This class provides functionality to determine whether or not all the
* required parameters have been set or not.
*
* @author coobird
*
*/
protected final static class ReadinessTracker
{
private final Map<String, Boolean> alreadySetMap =
new HashMap<String, Boolean>();
/**
* Returns whether or not the {@link ThumbnailMaker} has all its
* required parameter set to be able to make a thumbnail.
*
* @return {@code true} if the {@link ThumbnailMaker} is ready
* to make thumbnails, {@code false} otherwise.
*/
protected boolean isReady()
{
for (Map.Entry<String, Boolean> entry : alreadySetMap.entrySet())
{
if (!entry.getValue())
{
return false;
}
}
return true;
}
/**
* Tells the {@link ReadinessTracker} that the given parameter has not
* yet been set by the {@link ThumbnailMaker}.
*
* @param parameterName The parameter which has not been set.
*/
protected void unset(String parameterName)
{
alreadySetMap.put(parameterName, false);
}
/**
* Tells the {@link ReadinessTracker} that the given parameter has been
* set by the {@link ThumbnailMaker}.
*
* @param parameterName The parameter to be marked as being set.
*/
protected void set(String parameterName)
{
alreadySetMap.put(parameterName, true);
}
/**
* Returns whether the specified parameter has already been set.
*
* @param parameterName The parameter to check whether it has been
* already set or not
* @return {@code true} if the parameter has been set,
* {@code false} otherwise.
*/
protected boolean isSet(String parameterName)
{
return alreadySetMap.get(parameterName);
}
}
/**
* Object used to keep track whether the required parameters for creating
* a thumbnail has been set.
*/
protected final ReadinessTracker ready;
/**
* Default image type of the thumbnails created by {@link ThumbnailMaker}.
*/
private static final int DEFAULT_IMAGE_TYPE = BufferedImage.TYPE_INT_ARGB;
/**
* The image type of the resulting thumbnail.
*/
protected int imageType;
/**
* The {@link ResizerFactory} which is used to obtain a {@link Resizer}
* for the resizing operation.
* <p>
* By delaying the decision of picking the {@link Resizer} to use until
* when the thumbnail is to be created could lead to a more suitable
* {@link Resizer} being picked, as the dimensions for the source and
* destination images are known at that time.
*/
protected ResizerFactory resizerFactory;
/**
* Creates and initializes an instance of {@link ThumbnailMaker}.
*/
public ThumbnailMaker()
{
ready = new ReadinessTracker();
ready.unset(PARAM_IMAGE_TYPE);
ready.unset(PARAM_RESIZER);
ready.unset(PARAM_RESIZERFACTORY);
defaultImageType();
defaultResizerFactory();
}
/**
* Makes a thumbnail.
*
* @param img The source image.
* @return The thumbnail created from the source image, using the
* parameters set by the {@link ThumbnailMaker}.
*/
public abstract BufferedImage make(BufferedImage img);
/**
* Makes a thumbnail of the specified dimensions, from the specified
* source image.
*
* @param img The source image.
* @param width The target width of the thumbnail.
* @param height The target height of the thumbnail.
* @return The thumbnail image.
* @throws IllegalStateException If the {@code ThumbnailMaker} is
* not ready to create thumbnails.
* @throws IllegalArgumentException If the width and/or height is less
* than or equal to zero.
*/
protected BufferedImage makeThumbnail(
BufferedImage img,
int width,
int height
)
{
if (!ready.isReady())
{
throw new IllegalStateException(ThumbnailMaker.NOT_READY_FOR_MAKE);
}
if (width <= 0)
{
throw new IllegalArgumentException(
"Width must be greater than zero."
);
}
if (height <= 0)
{
throw new IllegalArgumentException(
"Height must be greater than zero."
);
}
BufferedImage thumbnailImage =
new BufferedImageBuilder(width, height, imageType).build();
Dimension imgSize = new Dimension(img.getWidth(), img.getHeight());
Dimension thumbnailSize = new Dimension(width, height);
Resizer resizer = resizerFactory.getResizer(imgSize, thumbnailSize);
resizer.resize(img, thumbnailImage);
return thumbnailImage;
}
/**
* Sets the type for the {@link BufferedImage} to produce.
*
* @param imageType The type of the {@code BufferedImage}.
* @return A reference to this object.
*/
public ThumbnailMaker imageType(int imageType)
{
this.imageType = imageType;
ready.set(PARAM_IMAGE_TYPE);
return this;
}
/**
* Sets the type of the {@link BufferedImage} to be the default type.
*
* @return A reference to this object.
*/
public ThumbnailMaker defaultImageType()
{
return imageType(DEFAULT_IMAGE_TYPE);
}
/**
* Sets the {@link Resizer} which is used for the resizing operation.
*
* @param resizer The {@link Resizer} to use when resizing the image
* to create the thumbnail.
* @return A reference to this object.
*/
public ThumbnailMaker resizer(Resizer resizer)
{
this.resizerFactory = new FixedResizerFactory(resizer);
ready.set(PARAM_RESIZER);
ready.set(PARAM_RESIZERFACTORY);
return this;
}
/**
* Sets the {@link Resizer} to use the default {@link Resizer}.
*
* @return A reference to this object.
*/
public ThumbnailMaker defaultResizer()
{
return defaultResizerFactory();
}
/**
* Sets the {@link ResizerFactory} which is used to obtain a {@link Resizer}
* for the resizing operation.
*
* @param resizerFactory The {@link ResizerFactory} to obtain the
* {@link Resizer} used when resizing the image
* to create the thumbnail.
* @return A reference to this object.
* @since 0.4.0
*/
public ThumbnailMaker resizerFactory(ResizerFactory resizerFactory)
{
this.resizerFactory = resizerFactory;
ready.set(PARAM_RESIZER);
ready.set(PARAM_RESIZERFACTORY);
return this;
}
/**
* Sets the {@link ResizerFactory} to use {@link DefaultResizerFactory}.
*
* @return A reference to this object.
* @since 0.4.0
*/
public ThumbnailMaker defaultResizerFactory()
{
this.resizerFactory = DefaultResizerFactory.getInstance();
ready.set(PARAM_RESIZER);
ready.set(PARAM_RESIZERFACTORY);
return this;
}
}
| Java |
package net.coobird.thumbnailator.makers;
import java.awt.image.BufferedImage;
/**
* A {@link ThumbnailMaker} which resizes an image to a specified dimension
* when producing a thumbnail.
* <p>
* Optionally, if the aspect ratio of the thumbnail is to be maintained the same
* as the original image (by calling the {@link #keepAspectRatio(boolean)}
* method with the value {@code true}), then the dimensions specified by the
* {@link #size(int, int)} method, {@link #FixedSizeThumbnailMaker(int, int)} or
* {@link #FixedSizeThumbnailMaker(int, int, boolean)} constructor will be used
* as the maximum constraint of dimensions of the thumbnail.
* <p>
* In other words, when the aspect ratio is to be kept constant, then
* thumbnails which are created will be sized to fit inside the dimensions
* specified by the size parameter.
* <p>
* Upon calculating the size of the thumbnail, if any of the dimensions are
* {@code 0}, then that dimension will be promoted to {@code 1}, regardless of
* whether the aspect ratio of the original image is to be maintained. This will
* lead to some thumbnails not preserving the aspect ratio of the original
* image, even if {@link #keepAspectRatio(boolean)} has been {@code true}.
* <p>
* <DL>
* <DT><B>Usage:</B></DT>
* <DD>
* The following example demonstrates how to create a thumbnail which fits
* within 200 pixels by 200 pixels, while preserving the aspect ratio of the
* source image:
* <pre>
BufferedImage img = ImageIO.read(new File("sourceImage.jpg"));
BufferedImage thumbnail = new FixedSizeThumbnailMaker()
.size(200, 200)
.keepAspectRatio(true)
.make(img);
* </pre>
* </DD>
* </DL>
*
* @author coobird
*
*/
public final class FixedSizeThumbnailMaker extends ThumbnailMaker
{
private static final String PARAM_SIZE = "size";
private static final String PARAM_KEEP_RATIO = "keepRatio";
private static final String PARAM_FIT_WITHIN = "fitWithinDimensions";
private int width;
private int height;
private boolean keepRatio;
private boolean fitWithinDimensions;
/**
* Creates a {@link FixedSizeThumbnailMaker}.
* <p>
* The size of the resulting thumbnail, and whether or not the aspect ratio
* of the original image should be maintained in the thumbnail must be
* set before this instance is able to produce thumbnails.
*/
public FixedSizeThumbnailMaker()
{
super();
ready.unset(PARAM_SIZE);
ready.unset(PARAM_KEEP_RATIO);
ready.unset(PARAM_FIT_WITHIN);
}
/**
* Creates a {@link FixedSizeThumbnailMaker} which creates thumbnails
* with the specified size.
* <p>
* Before this instance is able to produce thumbnails, whether or not the
* aspect ratio of the original image should be maintained in the thumbnail
* must be specified by calling the {@link #keepAspectRatio(boolean)}
* method.
*
* @param width The width of the thumbnail to produce.
* @param height The height of the thumbnails to produce.
*/
public FixedSizeThumbnailMaker(int width, int height)
{
this();
size(width, height);
}
/**
* Creates a {@link FixedSizeThumbnailMaker} which creates thumbnails
* with the specified size. Whether or not the aspect ratio of the original
* image should be preserved by the thumbnail is also specified at
* instantiation.
*
* @param width The width of the thumbnail to produce.
* @param height The height of the thumbnails to produce.
* @param aspectRatio Whether or not to maintain the aspect ratio in the
* thumbnail the same as the original image.
* <p>
* If {@code true} is specified, then the
* thumbnail image will have the same aspect ratio
* as the original image.
*/
public FixedSizeThumbnailMaker(int width, int height, boolean aspectRatio)
{
this();
size(width, height);
keepAspectRatio(aspectRatio);
}
/**
* Creates a {@link FixedSizeThumbnailMaker} which creates thumbnails
* with the specified size. Whether or not the aspect ratio of the original
* image should be preserved by the thumbnail, and whether to fit the
* thumbnail within the given dimensions is also specified at
* instantiation.
*
* @param width The width of the thumbnail to produce.
* @param height The height of the thumbnails to produce.
* @param aspectRatio Whether or not to maintain the aspect ratio in the
* thumbnail the same as the original image.
* <p>
* If {@code true} is specified, then the
* thumbnail image will have the same aspect ratio
* as the original image.
* @param fit Whether or not to fit the thumbnail within the
* specified dimensions.
* <p>
* If {@code true} is specified, then the thumbnail
* will be sized to fit within the specified
* {@code width} and {@code height}.
*/
public FixedSizeThumbnailMaker(int width, int height, boolean aspectRatio, boolean fit)
{
this();
size(width, height);
keepAspectRatio(aspectRatio);
fitWithinDimensions(fit);
}
/**
* Sets the size of the thumbnail to produce.
*
* @param width The width of the thumbnail to produce.
* @param height The height of the thumbnails to produce.
* @return A reference to this object.
* @throws IllegalStateException If the size has already
* been previously set, or if the
* {@code width} or {@code height} is less
* than or equal to zero.
*/
public FixedSizeThumbnailMaker size(int width, int height)
{
if (ready.isSet(PARAM_SIZE))
{
throw new IllegalStateException(
"The size has already been set."
);
}
if (width <= 0)
{
throw new IllegalArgumentException(
"Width must be greater than zero."
);
}
if (height <= 0)
{
throw new IllegalArgumentException(
"Height must be greater than zero."
);
}
this.width = width;
this.height = height;
ready.set(PARAM_SIZE);
return this;
}
/**
* Sets whether or not the thumbnail is to maintain the aspect ratio of
* the original image.
*
* @param keep Whether or not to maintain the aspect ratio in the
* thumbnail the same as the original image.
* <p>
* If {@code true} is specified, then the
* thumbnail image will have the same aspect ratio
* as the original image.
* @return A reference to this object.
* @throws IllegalStateException If whether to keep the aspect ratio has
* already been previously set.
*/
public FixedSizeThumbnailMaker keepAspectRatio(boolean keep)
{
if (ready.isSet(PARAM_KEEP_RATIO))
{
throw new IllegalStateException(
"Whether to keep the aspect ratio has already been set."
);
}
this.keepRatio = keep;
ready.set(PARAM_KEEP_RATIO);
return this;
}
/**
* Sets whether or not the thumbnail should fit within the specified
* dimensions.
* <p>
* When the dimensions of a thumbnail will exceed the specified dimensions,
* with the aspect ratio of the original being preserved, then if this
* method was called with {@code false}, then the resulting thumbnail will
* have the larger dimension align with the specified dimension, and the
* other will exceed the given dimension.
* <p>
* When {@link #keepAspectRatio(boolean)} is {@code false}, then calling
* this method with {@code true} or {@code false} makes no difference, as
* the thumbnail dimensions will be exactly the given dimensions.
*
* @param fit Whether or not to maintain the aspect ratio in the
* thumbnail the same as the original image.
* <p>
* If {@code true} is specified, then the
* thumbnail image will have the same aspect ratio
* as the original image.
* @return A reference to this object.
* @throws IllegalStateException If whether to keep the aspect ratio has
* already been previously set.
* @since 0.4.0
*/
public FixedSizeThumbnailMaker fitWithinDimensions(boolean fit)
{
if (ready.isSet(PARAM_FIT_WITHIN))
{
throw new IllegalStateException(
"Whether to fit within dimensions has already been set."
);
}
this.fitWithinDimensions = fit;
ready.set(PARAM_FIT_WITHIN);
return this;
}
@Override
public BufferedImage make(BufferedImage img)
{
int targetWidth = this.width;
int targetHeight = this.height;
if (keepRatio)
{
int sourceWidth = img.getWidth();
int sourceHeight = img.getHeight();
double sourceRatio = (double)sourceWidth / (double)sourceHeight;
double targetRatio = (double)targetWidth / (double)targetHeight;
/*
* If the ratios are not the same, then the appropriate
* width and height must be picked.
*/
if (Double.compare(sourceRatio, targetRatio) != 0)
{
if (fitWithinDimensions)
{
if (sourceRatio > targetRatio)
{
targetWidth = width;
targetHeight = (int)Math.round(targetWidth / sourceRatio);
}
else
{
targetWidth = (int)Math.round(targetHeight * sourceRatio);
targetHeight = height;
}
}
else
{
if (sourceRatio > targetRatio)
{
targetWidth = (int)Math.round(targetHeight * sourceRatio);
targetHeight = height;
}
else
{
targetWidth = width;
targetHeight = (int)Math.round(targetWidth / sourceRatio);
}
}
}
}
targetWidth = (targetWidth == 0) ? 1 : targetWidth;
targetHeight = (targetHeight == 0) ? 1 : targetHeight;
return super.makeThumbnail(img, targetWidth, targetHeight);
}
}
| Java |
/**
* This package provides classes which can be used to make thumbnails given
* parameters to create the images.
*/
package net.coobird.thumbnailator.makers;
| Java |
package net.coobird.thumbnailator.makers;
import java.awt.image.BufferedImage;
/**
* A {@link ThumbnailMaker} which scales an image by a specified scaling factor
* when producing a thumbnail.
* <p>
* Upon calculating the size of the thumbnail, if any of the dimensions are
* {@code 0}, then that dimension will be promoted to {@code 1}. This will
* cause some resizing operations to not preserve the aspect ratio of the
* original image.
* <p>
* <DL>
* <DT><B>Usage:</B></DT>
* <DD>
* The following example demonstrates how to create a thumbnail which is 25%
* the size of the source image:
* <pre>
BufferedImage img = ImageIO.read(new File("sourceImage.jpg"));
BufferedImage thumbnail = new ScaledThumbnailMaker()
.scale(0.25)
.make(img);
* </pre>
* </DD>
* </DL>
* It is also possible to independently specify the scaling factor for the
* width and height. (If the two scaling factors are not equal then the aspect
* ratio of the original image will not be preserved.)
* <p>
* <DL>
* <DT><B>Usage:</B></DT>
* <DD>
* The following example demonstrates how to create a thumbnail which is scaled
* 50% in the width and 75% in the height:
* <pre>
BufferedImage img = ImageIO.read(new File("sourceImage.jpg"));
BufferedImage thumbnail = new ScaledThumbnailMaker()
.scale(0.50, 0.75)
.make(img);
* </pre>
* </DD>
* </DL>
* <DL>
*
* @author coobird
*
*/
public final class ScaledThumbnailMaker extends ThumbnailMaker
{
private static final String PARAM_SCALE = "scale";
/**
* The scaling factor to apply to the width when resizing an image to
* create a thumbnail.
*/
private double widthFactor;
/**
* The scaling factor to apply to the height when resizing an image to
* create a thumbnail.
*/
private double heightFactor;
/**
* <p>
* Creates an instance of {@code ScaledThumbnailMaker} without the
* scaling factor specified.
* </p>
* <p>
* To use this {@code ScaledThumbnailMaker}, one must specify the
* scaling factor to use by calling the {@link #scale(double)} method
* before generating a thumbnail.
* </p>
*/
public ScaledThumbnailMaker()
{
super();
ready.unset(PARAM_SCALE);
}
/**
* Creates an instance of {@code ScaledThumbnailMaker} with the specified
* scaling factor.
*
* @param factor The scaling factor to apply when resizing an
* image to create a thumbnail.
*/
public ScaledThumbnailMaker(double factor)
{
this();
scale(factor);
}
/**
* Creates an instance of {@code ScaledThumbnailMaker} with the specified
* scaling factors for the width and height.
*
* @param widthFactor The scaling factor to apply to the width when
* resizing an image to create a thumbnail.
* @param heightFactor The scaling factor to apply to the height when
* resizing an image to create a thumbnail.
* @since 0.3.10
*/
public ScaledThumbnailMaker(double widthFactor, double heightFactor)
{
this();
scale(widthFactor, heightFactor);
}
/**
* <p>
* Sets the scaling factor for the thumbnail.
* </p>
* <p>
* The aspect ratio of the resulting image is unaltered from the original.
* </p>
*
* @param factor The scaling factor to apply when resizing an
* image to create a thumbnail.
* @return A reference to this object.
* @throws IllegalStateException If the scaling factor has already
* been previously set.
*/
public ScaledThumbnailMaker scale(double factor)
{
return scale(factor, factor);
}
/**
* <p>
* Sets the scaling factors for the thumbnail.
* </p>
*
* @param widthFactor The scaling factor to apply to the width when
* resizing an image to create a thumbnail.
* @param heightFactor The scaling factor to apply to the height when
* resizing an image to create a thumbnail.
* @return A reference to this object.
* @throws IllegalStateException If the scaling factor has already
* been previously set.
* @since 0.3.10
*/
public ScaledThumbnailMaker scale(double widthFactor, double heightFactor)
{
if (ready.isSet(PARAM_SCALE))
{
throw new IllegalStateException(
"The scaling factor has already been set."
);
}
if (widthFactor <= 0 || heightFactor <= 0)
{
throw new IllegalArgumentException(
"The scaling factor must be greater than zero."
);
}
this.widthFactor = widthFactor;
this.heightFactor = heightFactor;
ready.set(PARAM_SCALE);
return this;
}
@Override
public BufferedImage make(BufferedImage img)
{
int width = (int)Math.round(img.getWidth() * widthFactor);
int height = (int)Math.round(img.getHeight() * heightFactor);
width = (width == 0) ? 1 : width;
height = (height == 0) ? 1 : height;
return super.makeThumbnail(img, width, height);
}
}
| Java |
package net.coobird.thumbnailator.geometry;
import java.awt.Point;
/**
* This interface is implemented by classes which calculate how to position an
* object inside of an enclosing object.
*
* @author coobird
*
*/
public interface Position
{
/**
* Calculates the position of an object enclosed by an enclosing object.
*
* @param enclosingWidth The width of the enclosing object that is
* to contain the enclosed object.
* @param enclosingHeight The height of the enclosing object that is
* to contain the enclosed object.
* @param width The width of the object that is to be
* placed inside an enclosing object.
* @param height The height of the object that is to be
* placed inside an enclosing object.
* @param insetLeft The inset on the left-hand side of the
* object to be enclosed.
* @param insetRight The inset on the right-hand side of the
* object to be enclosed.
* @param insetTop The inset on the top side of the
* object to be enclosed.
* @param insetBottom The inset on the bottom side of the
* object to be enclosed.
* @return The position to place the object.
*/
public Point calculate(
int enclosingWidth, int enclosingHeight, int width, int height,
int insetLeft, int insetRight, int insetTop, int insetBottom
);
}
| Java |
package net.coobird.thumbnailator.geometry;
import java.awt.Point;
/**
* This class calculates the position of an image which is to be enclosed,
* using an absolute coordinate at which the image should be located.
*
* @author coobird
*
*/
public final class Coordinate implements Position
{
/**
* The horizontal position of the image to be enclosed.
*/
private final int x;
/**
* The vertical position of the image to be enclosed.
*/
private final int y;
/**
* Instantiates an object which calculates the position of an image, using
* the given coordinates.
*
* @param x The horizontal component of the top-left corner of the
* image to be enclosed.
* @param y The vertical component of the top-left corner of the
* image to be enclosed.
*/
public Coordinate(int x, int y)
{
this.x = x;
this.y = y;
}
public Point calculate(int enclosingWidth, int enclosingHeight, int width,
int height, int insetLeft, int insetRight, int insetTop,
int insetBottom)
{
int x = this.x + insetLeft;
int y = this.y + insetTop;
return new Point(x, y);
}
}
| Java |
/**
* This package contains classes used to specify positioning of watermarks and
* other objects in Thumbnailator.
*/
package net.coobird.thumbnailator.geometry;
| Java |
package net.coobird.thumbnailator.geometry;
import java.awt.Dimension;
/**
* A {@link Size} object which indicates that the size of the enclosed object
* should be the specified absolute size.
*
* @author coobird
* @since 0.3.4
*
*/
public class AbsoluteSize implements Size
{
/**
* The size of the object.
*/
private final Dimension size;
/**
* Instantiates an object which indicates size of an object.
*
* @param size Size of the enclosed object.
* @throws NullPointerException If the size is {@code null}.
*/
public AbsoluteSize(Dimension size)
{
if (size == null)
{
throw new NullPointerException("Size cannot be null.");
}
this.size = new Dimension(size);
}
/**
* Instantiates an object which indicates size of an object.
*
* @param width Width of the enclosed object.
* @param height Height of the enclosed object.
* @throws IllegalArgumentException If the width and/or height is less
* than or equal to {@code 0}.
*/
public AbsoluteSize(int width, int height)
{
if (width <= 0 || height <= 0)
{
throw new IllegalArgumentException(
"Width and height must be greater than 0."
);
}
this.size = new Dimension(width, height);
}
public Dimension calculate(int width, int height)
{
if (width <= 0 || height <= 0)
{
throw new IllegalArgumentException(
"Width and height must be greater than 0."
);
}
return new Dimension(size);
}
/**
* Returns a {@code String} representation of this object.
*
* @return {@code String} representation of this object.
*/
@Override
public String toString()
{
return "AbsoluteSize [width=" + size.width + ", height=" + size.height + "]";
}
}
| Java |
package net.coobird.thumbnailator.geometry;
import java.awt.Dimension;
/**
* Calculates the size of an enclosed object relative to the enclosing object.
*
* @author coobird
* @since 0.3.4
*
*/
public class RelativeSize implements Size
{
/**
* The scaling factor to use for the enclosed object.
*/
private final double scalingFactor;
/**
* Instantiates an object which calculates the size of an object, using
* the given scaling factor.
*
* @param scalingFactor The scaling factor to use to determine the
* size of the enclosing object.
* @throws IllegalArgumentException When the scaling factor is not within
* the range of {@code 0.0d} and
* {@code 1.0d}, inclusive.
*/
public RelativeSize(double scalingFactor)
{
super();
if (scalingFactor < 0.0d || scalingFactor > 1.0d)
{
throw new IllegalArgumentException(
"The scaling factor must be between 0.0d and 1.0d, inclusive."
);
}
this.scalingFactor = scalingFactor;
}
public Dimension calculate(int width, int height)
{
if (width <= 0 || height <= 0)
{
throw new IllegalArgumentException(
"Width and height must be greater than 0."
);
}
int newWidth = (int)Math.round(width * scalingFactor);
int newHeight = (int)Math.round(height * scalingFactor);
return new Dimension(newWidth, newHeight);
}
/**
* Returns a {@code String} representation of this object.
*
* @return {@code String} representation of this object.
*/
@Override
public String toString()
{
return "RelativeSize [scalingFactor=" + scalingFactor + "]";
}
}
| Java |
package net.coobird.thumbnailator.geometry;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
/**
* A representation of a region, using a {@link Position} object and a
* {@link Dimension} object.
*
* @author coobird
* @since 0.3.4
*
*/
public final class Region
{
/**
* Position of the region.
*/
private final Position position;
/**
* Size of the region.
*/
private final Size size;
/**
* Instantiates a representation of a region from a {@link Position} and
* {@link Size}.
*
* @param position Position of the region.
* @param size Size of the region.
* @throws NullPointerException When the position and/or the size is
* {@code null}.
*/
public Region(Position position, Size size)
{
super();
if (position == null)
{
throw new NullPointerException("Position cannot be null.");
}
if (size == null)
{
throw new NullPointerException("Size cannot be null.");
}
this.position = position;
this.size = size;
}
/**
* Returns the position of the region.
*
* @return Position of the region.
*/
public Position getPosition()
{
return position;
}
/**
* Returns the size of the region.
*
* @return Size of the region.
*/
public Size getSize()
{
return size;
}
/**
* Calculates the position and size of the enclosed region, relative to the
* enclosing region.
* <p>
* The portions of the enclosed region which lies outside of the enclosing
* region are ignored. Effectively, the {@link Rectangle} returned by this
* method is a intersection of the enclosing and enclose regions.
*
* @param width Width of the enclosing region.
* @param height Height of the enclosing region.
* @return Position and size of the enclosed region.
*/
public Rectangle calculate(int width, int height)
{
Dimension d = size.calculate(width, height);
Point p = position.calculate(
width, height, d.width, d.height, 0, 0, 0, 0
);
Rectangle outerRectangle = new Rectangle(0, 0, width, height);
Rectangle innerRectangle = new Rectangle(p, d);
return outerRectangle.intersection(innerRectangle);
}
/**
* Returns a {@code String} representation of this region.
*
* @return {@code String} representation of this region.
*/
@Override
public String toString()
{
return "Region [position=" + position + ", size=" + size + "]";
}
}
| Java |
package net.coobird.thumbnailator.geometry;
import java.awt.Point;
import net.coobird.thumbnailator.filters.Caption;
import net.coobird.thumbnailator.filters.ImageFilter;
import net.coobird.thumbnailator.filters.Watermark;
/**
* An enum of predefined {@link Position}s.
* <p>
* Primary use of this enum is for selecting a position to place watermarks
* (using the {@link Watermark} class), captions (using the {@link Caption}
* class) and other {@link ImageFilter}s.
*
* @author coobird
*
*/
public enum Positions implements Position
{
/**
* Calculates the {@link Point} at which an enclosed image should be placed
* if it is to be placed at the top left-hand corner of the enclosing
* image.
*/
TOP_LEFT()
{
public Point calculate(int enclosingWidth, int enclosingHeight,
int width, int height, int insetLeft, int insetRight,
int insetTop, int insetBottom)
{
int x = insetLeft;
int y = insetTop;
return new Point(x, y);
}
},
/**
* Calculates the {@link Point} at which an enclosed image should be placed
* if it is to be horizontally centered at the top of the enclosing image.
*/
TOP_CENTER()
{
public Point calculate(int enclosingWidth, int enclosingHeight,
int width, int height, int insetLeft, int insetRight,
int insetTop, int insetBottom)
{
int x = (enclosingWidth / 2) - (width / 2);
int y = insetTop;
return new Point(x, y);
}
},
/**
* Calculates the {@link Point} at which an enclosed image should be placed
* if it is to be placed at the top right-hand corner of the enclosing
* image.
*/
TOP_RIGHT()
{
public Point calculate(int enclosingWidth, int enclosingHeight,
int width, int height, int insetLeft, int insetRight,
int insetTop, int insetBottom)
{
int x = enclosingWidth - width - insetRight;
int y = insetTop;
return new Point(x, y);
}
},
/**
* Calculates the {@link Point} at which an enclosed image should be placed
* if it is to be placed vertically centered at the left-hand corner of
* the enclosing image.
*/
CENTER_LEFT()
{
public Point calculate(int enclosingWidth, int enclosingHeight,
int width, int height, int insetLeft, int insetRight,
int insetTop, int insetBottom)
{
int x = insetLeft;
int y = (enclosingHeight / 2) - (height / 2);
return new Point(x, y);
}
},
/**
* Calculates the {@link Point} at which an enclosed image should be placed
* horizontally and vertically centered in the enclosing image.
*/
CENTER()
{
public Point calculate(int enclosingWidth, int enclosingHeight,
int width, int height, int insetLeft, int insetRight,
int insetTop, int insetBottom)
{
int x = (enclosingWidth / 2) - (width / 2);
int y = (enclosingHeight / 2) - (height / 2);
return new Point(x, y);
}
},
/**
* Calculates the {@link Point} at which an enclosed image should be placed
* if it is to be placed vertically centered at the right-hand corner of
* the enclosing image.
*/
CENTER_RIGHT()
{
public Point calculate(int enclosingWidth, int enclosingHeight,
int width, int height, int insetLeft, int insetRight,
int insetTop, int insetBottom)
{
int x = enclosingWidth - width - insetRight;
int y = (enclosingHeight / 2) - (height / 2);
return new Point(x, y);
}
},
/**
* Calculates the {@link Point} at which an enclosed image should be placed
* if it is to be placed at the bottom left-hand corner of the enclosing
* image.
*/
BOTTOM_LEFT()
{
public Point calculate(int enclosingWidth, int enclosingHeight,
int width, int height, int insetLeft, int insetRight,
int insetTop, int insetBottom)
{
int x = insetLeft;
int y = enclosingHeight - height - insetBottom;
return new Point(x, y);
}
},
/**
* Calculates the {@link Point} at which an enclosed image should be placed
* if it is to be horizontally centered at the bottom of the enclosing
* image.
*/
BOTTOM_CENTER()
{
public Point calculate(int enclosingWidth, int enclosingHeight,
int width, int height, int insetLeft, int insetRight,
int insetTop, int insetBottom)
{
int x = (enclosingWidth / 2) - (width / 2);
int y = enclosingHeight - height - insetBottom;
return new Point(x, y);
}
},
/**
* Calculates the {@link Point} at which an enclosed image should be placed
* if it is to be placed at the bottom right-hand corner of the enclosing
* image.
*/
BOTTOM_RIGHT()
{
public Point calculate(int enclosingWidth, int enclosingHeight,
int width, int height, int insetLeft, int insetRight,
int insetTop, int insetBottom)
{
int x = enclosingWidth - width - insetRight;
int y = enclosingHeight - height - insetBottom;
return new Point(x, y);
}
},
;
}
| Java |
package net.coobird.thumbnailator.geometry;
import java.awt.Dimension;
/**
* This interface is implemented by classes which calculate the size of an
* object inside of an enclosing object.
*
* @author coobird
* @since 0.3.4
*
*/
public interface Size
{
/**
* Calculates the size of the object.
*
* @param width Width of the object which encloses the object
* for which the size should be determined.
* @param height Height of the object which encloses the object
* for which the size should be determined.
* @return Calculated size of the object.
* @throws IllegalArgumentException If the width and/or height is less than
* or equal to {@code 0}.
*/
public Dimension calculate(int width, int height);
}
| Java |
package net.coobird.thumbnailator;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.filters.Canvas;
import net.coobird.thumbnailator.filters.ImageFilter;
import net.coobird.thumbnailator.filters.Pipeline;
import net.coobird.thumbnailator.filters.Rotation;
import net.coobird.thumbnailator.filters.Watermark;
import net.coobird.thumbnailator.geometry.AbsoluteSize;
import net.coobird.thumbnailator.geometry.Coordinate;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;
import net.coobird.thumbnailator.geometry.Region;
import net.coobird.thumbnailator.geometry.Size;
import net.coobird.thumbnailator.name.Rename;
import net.coobird.thumbnailator.resizers.BicubicResizer;
import net.coobird.thumbnailator.resizers.BilinearResizer;
import net.coobird.thumbnailator.resizers.DefaultResizerFactory;
import net.coobird.thumbnailator.resizers.FixedResizerFactory;
import net.coobird.thumbnailator.resizers.ProgressiveBilinearResizer;
import net.coobird.thumbnailator.resizers.Resizer;
import net.coobird.thumbnailator.resizers.ResizerFactory;
import net.coobird.thumbnailator.resizers.configurations.AlphaInterpolation;
import net.coobird.thumbnailator.resizers.configurations.Antialiasing;
import net.coobird.thumbnailator.resizers.configurations.Dithering;
import net.coobird.thumbnailator.resizers.configurations.Rendering;
import net.coobird.thumbnailator.resizers.configurations.ScalingMode;
import net.coobird.thumbnailator.tasks.SourceSinkThumbnailTask;
import net.coobird.thumbnailator.tasks.io.BufferedImageSink;
import net.coobird.thumbnailator.tasks.io.BufferedImageSource;
import net.coobird.thumbnailator.tasks.io.FileImageSink;
import net.coobird.thumbnailator.tasks.io.FileImageSource;
import net.coobird.thumbnailator.tasks.io.ImageSource;
import net.coobird.thumbnailator.tasks.io.InputStreamImageSource;
import net.coobird.thumbnailator.tasks.io.OutputStreamImageSink;
import net.coobird.thumbnailator.tasks.io.URLImageSource;
import net.coobird.thumbnailator.util.ThumbnailatorUtils;
/**
* Provides a fluent interface to create thumbnails.
* <p>
* This is the main entry point for creating thumbnails with Thumbnailator.
* <p>
* By using the Thumbnailator's fluent interface, it is possible to write
* thumbnail generation code which resembles written English.
* <DL>
* <DT><B>Usage:</B></DT>
* <DD>
* The following example code demonstrates how to use the fluent interface
* to create a thumbnail from multiple files from a directory, resizing them to
* a maximum of 200 pixels by 200 pixels while preserving the aspect ratio of
* the original, then saving the resulting thumbnails as JPEG images with file
* names having {@code thumbnail.} appended to the beginning of the file name.
* <p>
* <pre>
Thumbnails.of(directory.listFiles())
.size(200, 200)
.outputFormat("jpeg")
.asFiles(Rename.PREFIX_DOT_THUMBNAIL);
// English: "Make thumbnails of files in the directory, with a size of 200x200,
with output format of JPEG, and save them as files while renaming
the files to be prefixed with a 'thumbnail.'."
* </pre>
* </DD>
* </DL>
* For more examples, please visit the <a href="http://code.google.com/p/thumbnailator/">
* Thumbnailator</a> project page.
* <p>
* <h2>Important Implementation Notes</h2>
* Upon calling one of the {@code Thumbnails.of(...)} methods, <em>in the
* current implementation</em>, an instance of an inner class of this class is
* returned. In most cases, the returned instance should not be used by
* storing it in a local variable, as changes in the internal implementation
* could break code in the future.
* <p>
* As a rule of thumb, <em>always method chain from the {@code Thumbnails.of}
* all the way until the output method (e.g. {@code toFile}, {@code asBufferedImage},
* etc.) is called without breaking them down into single statements.</em>
* See the "Usage" section above for the intended use of the Thumbnailator's
* fluent interface.
* <DL>
* <DT><B>Unintended Use:</B></DT>
* <DD>
* <pre>
// Unintended use - not recommended!
Builder<File> instance = Thumbnails.of("path/to/image");
instance.size(200, 200);
instance.asFiles("path/to/thumbnail");
* </pre>
* </DD>
* </DL>
*
* @author coobird
*
*/
public final class Thumbnails
{
/**
* This class is not intended to be instantiated.
*/
private Thumbnails() {}
/**
* Performs validation on the specified dimensions.
* <p>
* If any of the dimensions are less than or equal to 0, an
* {@code IllegalArgumentException} is thrown with an message specifying the
* reason for the exception.
* <p>
* This method is used to perform a check on the output dimensions of a
* thumbnail for the {@link Thumbnails#createThumbnail} methods.
*
* @param width The width to validate.
* @param height The height to validate.
*/
private static void validateDimensions(int width, int height)
{
if (width <= 0 && height <= 0)
{
throw new IllegalArgumentException(
"Destination image dimensions must not be less than " +
"0 pixels."
);
}
else if (width <= 0 || height <= 0)
{
String dimension = width == 0 ? "width" : "height";
throw new IllegalArgumentException(
"Destination image " + dimension + " must not be " +
"less than or equal to 0 pixels."
);
}
}
private static void checkForNull(Object o, String message)
{
if (o == null)
{
throw new NullPointerException(message);
}
}
private static void checkForEmpty(Object[] o, String message)
{
if (o.length == 0)
{
throw new IllegalArgumentException(message);
}
}
private static void checkForEmpty(Iterable<?> o, String message)
{
if (!o.iterator().hasNext())
{
throw new IllegalArgumentException(message);
}
}
/**
* Indicate to make thumbnails for images with the specified filenames.
*
* @param files File names of image files for which thumbnails
* are to be produced for.
* @return Reference to a builder object which is used to
* specify the parameters for creating the thumbnail.
* @throws NullPointerException If the argument is {@code null}.
* @throws IllegalArgumentException If the argument is an empty array.
*/
public static Builder<File> of(String... files)
{
checkForNull(files, "Cannot specify null for input files.");
checkForEmpty(files, "Cannot specify an empty array for input files.");
return Builder.ofStrings(Arrays.asList(files));
}
/**
* Indicate to make thumbnails from the specified {@link File}s.
*
* @param files {@link File} objects of image files for which thumbnails
* are to be produced for.
* @return Reference to a builder object which is used to
* specify the parameters for creating the thumbnail.
* @throws NullPointerException If the argument is {@code null}.
* @throws IllegalArgumentException If the argument is an empty array.
*/
public static Builder<File> of(File... files)
{
checkForNull(files, "Cannot specify null for input files.");
checkForEmpty(files, "Cannot specify an empty array for input files.");
return Builder.ofFiles(Arrays.asList(files));
}
/**
* Indicate to make thumbnails from the specified {@link URL}s.
*
* @param urls {@link URL} objects of image files for which thumbnails
* are to be produced for.
* @return Reference to a builder object which is used to
* specify the parameters for creating the thumbnail.
* @throws NullPointerException If the argument is {@code null}.
* @throws IllegalArgumentException If the argument is an empty array.
*/
public static Builder<URL> of(URL... urls)
{
checkForNull(urls, "Cannot specify null for input URLs.");
checkForEmpty(urls, "Cannot specify an empty array for input URLs.");
return Builder.ofUrls(Arrays.asList(urls));
}
/**
* Indicate to make thumbnails from the specified {@link InputStream}s.
*
* @param inputStreams {@link InputStream}s which provide the images
* for which thumbnails are to be produced for.
* @return Reference to a builder object which is used to
* specify the parameters for creating the thumbnail.
* @throws NullPointerException If the argument is {@code null}.
* @throws IllegalArgumentException If the argument is an empty array.
*/
public static Builder<? extends InputStream> of(InputStream... inputStreams)
{
checkForNull(inputStreams, "Cannot specify null for InputStreams.");
checkForEmpty(inputStreams, "Cannot specify an empty array for InputStreams.");
return Builder.ofInputStreams(Arrays.asList(inputStreams));
}
/**
* Indicate to make thumbnails from the specified {@link BufferedImage}s.
*
* @param images {@link BufferedImage}s for which thumbnails
* are to be produced for.
* @return Reference to a builder object which is used to
* specify the parameters for creating the thumbnail.
* @throws NullPointerException If the argument is {@code null}.
* @throws IllegalArgumentException If the argument is an empty array.
*/
public static Builder<BufferedImage> of(BufferedImage... images)
{
checkForNull(images, "Cannot specify null for images.");
checkForEmpty(images, "Cannot specify an empty array for images.");
return Builder.ofBufferedImages(Arrays.asList(images));
}
/**
* Indicate to make thumbnails for images with the specified filenames.
*
* @param files File names of image files for which thumbnails
* are to be produced for.
* @return Reference to a builder object which is used to
* specify the parameters for creating the thumbnail.
* @throws NullPointerException If the argument is {@code null}.
* @throws IllegalArgumentException If the argument is an empty collection.
* @since 0.3.1
*/
public static Builder<File> fromFilenames(Iterable<String> files)
{
checkForNull(files, "Cannot specify null for input files.");
checkForEmpty(files, "Cannot specify an empty collection for input files.");
return Builder.ofStrings(files);
}
/**
* Indicate to make thumbnails from the specified {@link File}s.
*
* @param files {@link File} objects of image files for which thumbnails
* are to be produced for.
* @return Reference to a builder object which is used to
* specify the parameters for creating the thumbnail.
* @throws NullPointerException If the argument is {@code null}.
* @throws IllegalArgumentException If the argument is an empty collection.
* @since 0.3.1
*/
public static Builder<File> fromFiles(Iterable<File> files)
{
checkForNull(files, "Cannot specify null for input files.");
checkForEmpty(files, "Cannot specify an empty collection for input files.");
return Builder.ofFiles(files);
}
/**
* Indicate to make thumbnails for images with the specified {@link URL}s.
*
* @param urls URLs of the images for which thumbnails
* are to be produced.
* @return Reference to a builder object which is used to
* specify the parameters for creating the thumbnail.
* @throws NullPointerException If the argument is {@code null}.
* @throws IllegalArgumentException If the argument is an empty collection.
* @since 0.3.1
*/
public static Builder<URL> fromURLs(Iterable<URL> urls)
{
checkForNull(urls, "Cannot specify null for input URLs.");
checkForEmpty(urls, "Cannot specify an empty collection for input URLs.");
return Builder.ofUrls(urls);
}
/**
* Indicate to make thumbnails for images obtained from the specified
* {@link InputStream}s.
*
* @param inputStreams {@link InputStream}s which provide images for
* which thumbnails are to be produced.
* @return Reference to a builder object which is used to
* specify the parameters for creating the thumbnail.
* @throws NullPointerException If the argument is {@code null}.
* @throws IllegalArgumentException If the argument is an empty collection.
* @since 0.3.1
*/
public static Builder<InputStream> fromInputStreams(Iterable<? extends InputStream> inputStreams)
{
checkForNull(inputStreams, "Cannot specify null for InputStreams.");
checkForEmpty(inputStreams, "Cannot specify an empty collection for InputStreams.");
return Builder.ofInputStreams(inputStreams);
}
/**
* Indicate to make thumbnails from the specified {@link BufferedImage}s.
*
* @param images {@link BufferedImage}s for which thumbnails
* are to be produced for.
* @return Reference to a builder object which is used to
* specify the parameters for creating the thumbnail.
* @throws NullPointerException If the argument is {@code null}.
* @throws IllegalArgumentException If the argument is an empty collection.
* @since 0.3.1
*/
public static Builder<BufferedImage> fromImages(Iterable<BufferedImage> images)
{
checkForNull(images, "Cannot specify null for images.");
checkForEmpty(images, "Cannot specify an empty collection for images.");
return Builder.ofBufferedImages(images);
}
/**
* The builder interface for Thumbnailator to set up the thumbnail
* generation task.
* <p>
* Thumbnailator is intended to be used by calling one of the
* {@code Thumbnails.of(...)} methods, then chaining methods such as
* {@link #size(int, int)} and {@link #outputQuality(double)} to set up
* the thumbnail generation parameters. (See "Intended Use" below.)
* The end result should be code that resembles English.
* <p>
* In most cases, holding an instance of this class in a local variable,
* such as seen in the "Unintended Use" example below, is more verbose
* and less future-proof, as changes to this class (which is just an
* inner class of the {@link Thumbnails} class) can lead to broken code
* when attempting to use future releases of Thumbnailator.
* <p>
* <DL>
* <DT><B>Intended Use:</B></DT>
* <DD>
* <pre>
// Intended use - recommended!
Thumbnails.of("path/to/image")
.size(200, 200)
.asFile("path/to/thumbnail");
// English: "Make a thumbnail of 'path/to/image' with a size of 200x200,
and save it as a file to 'path/to/thumbnail'."
* </pre>
* </DD>
* <DT><B>Unintended Use:</B></DT>
* <DD>
* <pre>
// Unintended use - not recommended!
Builder<File> instance = Thumbnails.of("path/to/image");
instance.size(200, 200);
instance.asFiles("path/to/thumbnail");
* </pre>
* </DD>
* </DL>
* <p>
* An instance of this class provides the fluent interface in the form of
* method chaining. Through the fluent interface, the parameters used for
* the thumbnail creation, such as {@link #size(int, int)} and
* {@link #outputQuality(double)} can be set up. Finally, to execute the
* thumbnail creation, one of the output methods whose names start with
* {@code to} (e.g. {@link #toFiles(Rename)}) or {@code as}
* (e.g. {@link #asBufferedImages()}) is called.
* <p>
* An instance of this class is obtained by calling one of:
* <ul>
* <li>{@link Thumbnails#of(BufferedImage...)}</li>
* <li>{@link Thumbnails#of(File...)}</li>
* <li>{@link Thumbnails#of(String...)}</li>
* <li>{@link Thumbnails#of(InputStream...)}</li>
* <li>{@link Thumbnails#of(URL...)}</li>
* <li>{@link Thumbnails#fromImages(Iterable)}</li>
* <li>{@link Thumbnails#fromFiles(Iterable)}</li>
* <li>{@link Thumbnails#fromFilenames(Iterable)}</li>
* <li>{@link Thumbnails#fromInputStreams(Iterable)}</li>
* <li>{@link Thumbnails#fromURLs(Iterable)}</li>
* </ul>
*
* @author coobird
*
*/
public static class Builder<T>
{
private final Iterable<ImageSource<T>> sources;
private Builder(Iterable<ImageSource<T>> sources)
{
this.sources = sources;
statusMap.put(Properties.OUTPUT_FORMAT, Status.OPTIONAL);
}
private static final class StringImageSourceIterator implements
Iterable<ImageSource<File>>
{
private final Iterable<String> filenames;
private StringImageSourceIterator(Iterable<String> filenames)
{
this.filenames = filenames;
}
public Iterator<ImageSource<File>> iterator()
{
return new Iterator<ImageSource<File>>() {
Iterator<String> iter = filenames.iterator();
public boolean hasNext()
{
return iter.hasNext();
}
public ImageSource<File> next()
{
return new FileImageSource(iter.next());
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
}
private static final class FileImageSourceIterator implements
Iterable<ImageSource<File>>
{
private final Iterable<File> files;
private FileImageSourceIterator(Iterable<File> files)
{
this.files = files;
}
public Iterator<ImageSource<File>> iterator()
{
return new Iterator<ImageSource<File>>() {
Iterator<File> iter = files.iterator();
public boolean hasNext()
{
return iter.hasNext();
}
public ImageSource<File> next()
{
return new FileImageSource(iter.next());
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
}
private static final class URLImageSourceIterator implements
Iterable<ImageSource<URL>>
{
private final Iterable<URL> urls;
private URLImageSourceIterator(Iterable<URL> urls)
{
this.urls = urls;
}
public Iterator<ImageSource<URL>> iterator()
{
return new Iterator<ImageSource<URL>>() {
Iterator<URL> iter = urls.iterator();
public boolean hasNext()
{
return iter.hasNext();
}
public ImageSource<URL> next()
{
return new URLImageSource(iter.next());
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
}
private static final class InputStreamImageSourceIterator implements
Iterable<ImageSource<InputStream>>
{
private final Iterable<? extends InputStream> inputStreams;
private InputStreamImageSourceIterator(Iterable<? extends InputStream> inputStreams)
{
this.inputStreams = inputStreams;
}
public Iterator<ImageSource<InputStream>> iterator()
{
return new Iterator<ImageSource<InputStream>>() {
Iterator<? extends InputStream> iter = inputStreams.iterator();
public boolean hasNext()
{
return iter.hasNext();
}
public ImageSource<InputStream> next()
{
return new InputStreamImageSource(iter.next());
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
}
private static final class BufferedImageImageSourceIterator implements
Iterable<ImageSource<BufferedImage>>
{
private final Iterable<BufferedImage> image;
private BufferedImageImageSourceIterator(Iterable<BufferedImage> images)
{
this.image = images;
}
public Iterator<ImageSource<BufferedImage>> iterator()
{
return new Iterator<ImageSource<BufferedImage>>() {
Iterator<BufferedImage> iter = image.iterator();
public boolean hasNext()
{
return iter.hasNext();
}
public ImageSource<BufferedImage> next()
{
return new BufferedImageSource(iter.next());
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
}
private static Builder<File> ofStrings(Iterable<String> filenames)
{
Iterable<ImageSource<File>> iter = new StringImageSourceIterator(filenames);
return new Builder<File>(iter);
}
private static Builder<File> ofFiles(Iterable<File> files)
{
Iterable<ImageSource<File>> iter = new FileImageSourceIterator(files);
return new Builder<File>(iter);
}
private static Builder<URL> ofUrls(Iterable<URL> urls)
{
Iterable<ImageSource<URL>> iter = new URLImageSourceIterator(urls);
return new Builder<URL>(iter);
}
private static Builder<InputStream> ofInputStreams(Iterable<? extends InputStream> inputStreams)
{
Iterable<ImageSource<InputStream>> iter = new InputStreamImageSourceIterator(inputStreams);
return new Builder<InputStream>(iter);
}
private static Builder<BufferedImage> ofBufferedImages(Iterable<BufferedImage> images)
{
Iterable<ImageSource<BufferedImage>> iter = new BufferedImageImageSourceIterator(images);
return new Builder<BufferedImage>(iter);
}
private final class BufferedImageIterable implements
Iterable<BufferedImage>
{
public Iterator<BufferedImage> iterator()
{
return new Iterator<BufferedImage>() {
Iterator<ImageSource<T>> sourceIter = sources.iterator();
public boolean hasNext()
{
return sourceIter.hasNext();
}
public BufferedImage next()
{
ImageSource<T> source = sourceIter.next();
BufferedImageSink destination = new BufferedImageSink();
try
{
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<T, BufferedImage>(makeParam(), source, destination)
);
}
catch (IOException e)
{
return null;
}
return destination.getSink();
}
public void remove()
{
throw new UnsupportedOperationException(
"Cannot remove elements from this iterator."
);
}
};
}
}
/**
* Status of each property.
*
* @author coobird
*
*/
private static enum Status
{
OPTIONAL,
READY,
NOT_READY,
ALREADY_SET,
CANNOT_SET,
}
/**
* Interface used by {@link Properties}.
*
* @author coobird
*
*/
private static interface Property
{
public String getName();
}
/**
* Enum of properties which can be set by this builder.
*
* @author coobird
*
*/
private static enum Properties implements Property
{
SIZE("size"),
WIDTH("width"),
HEIGHT("height"),
SCALE("scale"),
IMAGE_TYPE("imageType"),
SCALING_MODE("scalingMode"),
ALPHA_INTERPOLATION("alphaInterpolation"),
ANTIALIASING("antialiasing"),
DITHERING("dithering"),
RENDERING("rendering"),
KEEP_ASPECT_RATIO("keepAspectRatio"),
OUTPUT_FORMAT("outputFormat"),
OUTPUT_FORMAT_TYPE("outputFormatType"),
OUTPUT_QUALITY("outputQuality"),
RESIZER("resizer"),
SOURCE_REGION("sourceRegion"),
RESIZER_FACTORY("resizerFactory"),
ALLOW_OVERWRITE("allowOverwrite"),
CROP("crop"),
USE_EXIF_ORIENTATION("useExifOrientation"),
;
private final String name;
private Properties(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
/**
* Map to keep track of whether a property has been properly set or not.
*/
private final Map<Properties, Status> statusMap = new HashMap<Properties, Status>();
/**
* Populates the property map.
*/
{
statusMap.put(Properties.SIZE, Status.NOT_READY);
statusMap.put(Properties.WIDTH, Status.OPTIONAL);
statusMap.put(Properties.HEIGHT, Status.OPTIONAL);
statusMap.put(Properties.SCALE, Status.NOT_READY);
statusMap.put(Properties.SOURCE_REGION, Status.OPTIONAL);
statusMap.put(Properties.IMAGE_TYPE, Status.OPTIONAL);
statusMap.put(Properties.SCALING_MODE, Status.OPTIONAL);
statusMap.put(Properties.ALPHA_INTERPOLATION, Status.OPTIONAL);
statusMap.put(Properties.ANTIALIASING, Status.OPTIONAL);
statusMap.put(Properties.DITHERING, Status.OPTIONAL);
statusMap.put(Properties.RENDERING, Status.OPTIONAL);
statusMap.put(Properties.KEEP_ASPECT_RATIO, Status.OPTIONAL);
statusMap.put(Properties.OUTPUT_FORMAT, Status.OPTIONAL);
statusMap.put(Properties.OUTPUT_FORMAT_TYPE, Status.OPTIONAL);
statusMap.put(Properties.OUTPUT_QUALITY, Status.OPTIONAL);
statusMap.put(Properties.RESIZER, Status.OPTIONAL);
statusMap.put(Properties.RESIZER_FACTORY, Status.OPTIONAL);
statusMap.put(Properties.ALLOW_OVERWRITE, Status.OPTIONAL);
statusMap.put(Properties.CROP, Status.OPTIONAL);
statusMap.put(Properties.USE_EXIF_ORIENTATION, Status.OPTIONAL);
}
/**
* Updates the property status map.
*
* @param property The property to update.
* @param newStatus The new status.
*/
private void updateStatus(Properties property, Status newStatus)
{
if (statusMap.get(property) == Status.ALREADY_SET)
{
throw new IllegalStateException(
property.getName() + " is already set.");
}
/*
* The `newStatus != Status.CANNOT_SET` condition will allow the
* status to be set to CANNOT_SET to be set multiple times.
*/
if (newStatus != Status.CANNOT_SET && statusMap.get(property) == Status.CANNOT_SET)
{
throw new IllegalStateException(
property.getName() + " cannot be set.");
}
statusMap.put(property, newStatus);
}
/**
* An constant used to indicate that the imageType has not been
* specified. When this constant is encountered, one should use the
* {@link ThumbnailParameter#DEFAULT_IMAGE_TYPE} as the value for
* imageType.
*/
private static int IMAGE_TYPE_UNSPECIFIED = -1;
private static final int DIMENSION_NOT_SPECIFIED = -1;
/*
* Defines the fields for the builder interface, and assigns the
* default values.
*/
private int width = DIMENSION_NOT_SPECIFIED;
private int height = DIMENSION_NOT_SPECIFIED;
private double scaleWidth = Double.NaN;
private double scaleHeight = Double.NaN;
private Region sourceRegion;
private int imageType = IMAGE_TYPE_UNSPECIFIED;
private boolean keepAspectRatio = true;
private String outputFormat = ThumbnailParameter.DETERMINE_FORMAT;
private String outputFormatType = ThumbnailParameter.DEFAULT_FORMAT_TYPE;
private float outputQuality = ThumbnailParameter.DEFAULT_QUALITY;
private ScalingMode scalingMode = ScalingMode.PROGRESSIVE_BILINEAR;
private AlphaInterpolation alphaInterpolation = AlphaInterpolation.DEFAULT;
private Dithering dithering = Dithering.DEFAULT;
private Antialiasing antialiasing = Antialiasing.DEFAULT;
private Rendering rendering = Rendering.DEFAULT;
private ResizerFactory resizerFactory = DefaultResizerFactory.getInstance();
private boolean allowOverwrite = true;
private boolean fitWithinDimenions = true;
private boolean useExifOrientation = true;
/**
* This field should be set to the {@link Position} to be used for
* cropping if cropping is enabled. If cropping is disabled, then
* this field should be left {@code null}.
*/
private Position croppingPosition = null;
/**
* The {@link ImageFilter}s that should be applied when creating the
* thumbnail.
*/
private Pipeline filterPipeline = new Pipeline();
/**
* Sets the size of the thumbnail.
* <p>
* For example, to create thumbnails which should fit within a
* bounding rectangle of 640 x 480, the following code can be used:
* <pre><code>
Thumbnails.of(image)
.size(640, 480)
.toFile(thumbnail);
* </code></pre>
* <p>
* In the above code, the thumbnail will preserve the aspect ratio
* of the original image. If the thumbnail should be forced to the
* specified size, the {@link #forceSize(int, int)} method can
* be used instead of this method.
* <p>
* Once this method is called, calling the {@link #scale(double)} method
* will result in an {@link IllegalStateException}.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param width The width of the thumbnail.
* @param height The height of the thumbnail.
* @return Reference to this object.
*/
public Builder<T> size(int width, int height)
{
updateStatus(Properties.SIZE, Status.ALREADY_SET);
updateStatus(Properties.SCALE, Status.CANNOT_SET);
validateDimensions(width, height);
this.width = width;
this.height = height;
return this;
}
/**
* Sets the width of the thumbnail.
* <p>
* The thumbnail will have the dimensions constrained by the specified
* width, and the aspect ratio of the original image will be preserved
* by the thumbnail.
* <p>
* Once this method is called, calling the {@link #size(int, int)} or
* the {@link #scale(double)} method will result in an
* {@link IllegalStateException}.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param width The width of the thumbnail.
* @return Reference to this object.
* @since 0.3.5
*/
public Builder<T> width(int width)
{
if (statusMap.get(Properties.SIZE) != Status.CANNOT_SET)
{
updateStatus(Properties.SIZE, Status.CANNOT_SET);
}
if (statusMap.get(Properties.SCALE) != Status.CANNOT_SET)
{
updateStatus(Properties.SCALE, Status.CANNOT_SET);
}
updateStatus(Properties.WIDTH, Status.ALREADY_SET);
validateDimensions(width, Integer.MAX_VALUE);
this.width = width;
return this;
}
/**
* Sets the height of the thumbnail.
* <p>
* The thumbnail will have the dimensions constrained by the specified
* height, and the aspect ratio of the original image will be preserved
* by the thumbnail.
* <p>
* Once this method is called, calling the {@link #size(int, int)} or
* the {@link #scale(double)} method will result in an
* {@link IllegalStateException}.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param height The height of the thumbnail.
* @return Reference to this object.
* @since 0.3.5
*/
public Builder<T> height(int height)
{
if (statusMap.get(Properties.SIZE) != Status.CANNOT_SET)
{
updateStatus(Properties.SIZE, Status.CANNOT_SET);
}
if (statusMap.get(Properties.SCALE) != Status.CANNOT_SET)
{
updateStatus(Properties.SCALE, Status.CANNOT_SET);
}
updateStatus(Properties.HEIGHT, Status.ALREADY_SET);
validateDimensions(Integer.MAX_VALUE, height);
this.height = height;
return this;
}
/**
* Sets the size of the thumbnail.
* <p>
* The thumbnails will be forced to the specified size, therefore,
* the aspect ratio of the original image will not be preserved in
* the thumbnails. Calling this method will be equivalent to calling
* the {@link #size(int, int)} method in conjunction with the
* {@link #keepAspectRatio(boolean)} method with the value {@code false}.
* <p>
* Once this method is called, calling the {@link #scale(double)} method
* will result in an {@link IllegalStateException}.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param width The width of the thumbnail.
* @param height The height of the thumbnail.
* @return Reference to this object.
* @since 0.3.2
*/
public Builder<T> forceSize(int width, int height)
{
updateStatus(Properties.SIZE, Status.ALREADY_SET);
updateStatus(Properties.KEEP_ASPECT_RATIO, Status.ALREADY_SET);
updateStatus(Properties.SCALE, Status.CANNOT_SET);
validateDimensions(width, height);
this.width = width;
this.height = height;
this.keepAspectRatio = false;
return this;
}
/**
* Sets the scaling factor of the thumbnail.
* <p>
* For example, to create thumbnails which are 50% the size of the
* original, the following code can be used:
* <pre><code>
Thumbnails.of(image)
.scale(0.5)
.toFile(thumbnail);
* </code></pre>
* <p>
* Once this method is called, calling the {@link #size(int, int)}
* method, or the {@link #scale(double, double)} method, or the
* {@link #keepAspectRatio(boolean)} method will result in an
* {@link IllegalStateException}.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param scale The scaling factor to use when creating a
* thumbnail.
* <p>
* The value must be a {@code double} which is
* greater than {@code 0.0}, and not
* {@link Double#POSITIVE_INFINITY}.
* @return Reference to this object.
*/
public Builder<T> scale(double scale)
{
return scale(scale, scale);
}
/**
* Sets the scaling factor for the width and height of the thumbnail.
* <p>
* If the scaling factor for the width and height are not equal, then
* the thumbnail will not preserve the aspect ratio of the original
* image.
* <p>
* For example, to create thumbnails which are 50% the width of the
* original, while 75% the height of the original, the following code
* can be used:
* <pre><code>
Thumbnails.of(image)
.scale(0.5, 0.75)
.toFile(thumbnail);
* </code></pre>
* <p>
* Once this method is called, calling the {@link #size(int, int)}
* method, or the {@link #scale(double)} method, or the
* {@link #keepAspectRatio(boolean)} method will result in an
* {@link IllegalStateException}.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param scaleWidth The scaling factor to use for the width when
* creating a thumbnail.
* <p>
* The value must be a {@code double} which is
* greater than {@code 0.0}, and not
* {@link Double#POSITIVE_INFINITY}.
* @param scaleHeight The scaling factor to use for the height when
* creating a thumbnail.
* <p>
* The value must be a {@code double} which is
* greater than {@code 0.0}, and not
* {@link Double#POSITIVE_INFINITY}.
* @return Reference to this object.
* @since 0.3.10
*/
public Builder<T> scale(double scaleWidth, double scaleHeight)
{
updateStatus(Properties.SCALE, Status.ALREADY_SET);
updateStatus(Properties.SIZE, Status.CANNOT_SET);
updateStatus(Properties.KEEP_ASPECT_RATIO, Status.CANNOT_SET);
if (scaleWidth <= 0.0 || scaleHeight <= 0.0)
{
throw new IllegalArgumentException(
"The scaling factor is equal to or less than 0."
);
}
if (Double.isNaN(scaleWidth) || Double.isNaN(scaleHeight))
{
throw new IllegalArgumentException(
"The scaling factor is not a number."
);
}
if (Double.isInfinite(scaleWidth) || Double.isInfinite(scaleHeight))
{
throw new IllegalArgumentException(
"The scaling factor cannot be infinity."
);
}
this.scaleWidth = scaleWidth;
this.scaleHeight = scaleHeight;
return this;
}
/**
* Specifies the source region from which the thumbnail is to be
* created from.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param sourceRegion Source region to use when creating a thumbnail.
* <p>
* @return Reference to this object.
* @throws NullPointerException If the source region object is
* {@code null}.
* @since 0.3.4
*/
public Builder<T> sourceRegion(Region sourceRegion)
{
if (sourceRegion == null)
{
throw new NullPointerException("Region cannot be null.");
}
updateStatus(Properties.SOURCE_REGION, Status.ALREADY_SET);
this.sourceRegion = sourceRegion;
return this;
}
/**
* Specifies the source region from which the thumbnail is to be
* created from.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param position Position of the source region.
* @param size Size of the source region.
* @return Reference to this object.
* @throws NullPointerException If the position and/or size is
* {@code null}.
* @since 0.3.4
*/
public Builder<T> sourceRegion(Position position, Size size)
{
if (position == null)
{
throw new NullPointerException("Position cannot be null.");
}
if (size == null)
{
throw new NullPointerException("Size cannot be null.");
}
return sourceRegion(new Region(position, size));
}
/**
* Specifies the source region from which the thumbnail is to be
* created from.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param x The horizontal-compoennt of the top left-hand
* corner of the source region.
* @param y The vertical-compoennt of the top left-hand
* corner of the source region.
* @param width Width of the source region.
* @param height Height of the source region.
* @return Reference to this object.
* @throws IllegalArgumentException If the width and/or height is
* less than or equal to {@code 0}.
* @since 0.3.4
*/
public Builder<T> sourceRegion(int x, int y, int width, int height)
{
if (width <= 0 || height <= 0)
{
throw new IllegalArgumentException(
"Width and height must be greater than 0."
);
}
return sourceRegion(
new Coordinate(x, y),
new AbsoluteSize(width, height)
);
}
/**
* Specifies the source region from which the thumbnail is to be
* created from.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param position Position of the source region.
* @param width Width of the source region.
* @param height Height of the source region.
* @return Reference to this object.
* @throws NullPointerException If the position and/or size is
* {@code null}.
* @throws IllegalArgumentException If the width and/or height is
* less than or equal to {@code 0}.
* @since 0.3.4
*/
public Builder<T> sourceRegion(Position position, int width, int height)
{
if (position == null)
{
throw new NullPointerException("Position cannot be null.");
}
if (width <= 0 || height <= 0)
{
throw new IllegalArgumentException(
"Width and height must be greater than 0."
);
}
return sourceRegion(
position,
new AbsoluteSize(width, height)
);
}
/**
* Specifies the source region from which the thumbnail is to be
* created from.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param region A rectangular region which specifies the source
* region to use when creating the thumbnail.
* @throws NullPointerException If the region is {@code null}.
* @since 0.3.4
*/
public Builder<T> sourceRegion(Rectangle region)
{
if (region == null)
{
throw new NullPointerException("Region cannot be null.");
}
return sourceRegion(
new Coordinate(region.x, region.y),
new AbsoluteSize(region.getSize())
);
}
/**
* Crops the thumbnail to the size specified when calling the
* {@link #size(int, int)} method, positioned by the given
* {@link Position} object.
* <p>
* Calling this method will guarantee that the size of the thumbnail
* will be exactly the dimensions specified in the
* {@link #size(int, int)} method.
* <p>
* Internally, the resizing is performed in two steps.
* First, the thumbnail will be sized so that one of the dimensions will
* be sized exactly to the dimension specified in the {@code size}
* method, while allowing the other dimension to overhang the specified
* dimension. Then, the thumbnail will be cropped to the dimensions
* specified in the {@code size} method, positioned using the speficied
* {@link Position} object.
* <p>
* Once this method is called, calling the {@link #scale(double)} method
* will result in an {@link IllegalStateException}.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param position The position to which the thumbnail should be
* cropped to. For example, if
* {@link Positions#CENTER} is specified, the
* resulting thumbnail will be made by cropping to
* the center of the image.
* @throws NullPointerException If the position is {@code null}.
* @since 0.4.0
*/
public Builder<T> crop(Position position)
{
checkForNull(position, "Position cannot be null.");
updateStatus(Properties.CROP, Status.ALREADY_SET);
updateStatus(Properties.SCALE, Status.CANNOT_SET);
croppingPosition = position;
fitWithinDimenions = false;
return this;
}
/**
* Specifies whether or not to overwrite files which already exist if
* they have been specified as destination files.
* <p>
* This method will change the output behavior of the following methods:
* <ul>
* <li>{@link #toFile(File)}</li>
* <li>{@link #toFile(String)}</li>
* <li>{@link #toFiles(Iterable)}</li>
* <li>{@link #toFiles(Rename)}</li>
* <li>{@link #asFiles(Iterable)}</li>
* <li>{@link #asFiles(Rename)}</li>
* </ul>
* The behavior of methods which are not listed above will not be
* affected by calling this method.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param allowOverwrite If {@code true} then existing files will be
* overwritten if specified as a destination.
* If {@code false}, then the existing files
* will not be altered. For specific behavior,
* please refer to the specific output methods
* listed above.
*
* @since 0.3.7
*/
public Builder<T> allowOverwrite(boolean allowOverwrite)
{
updateStatus(Properties.ALLOW_OVERWRITE, Status.ALREADY_SET);
this.allowOverwrite = allowOverwrite;
return this;
}
/**
* Sets the image type of the thumbnail.
* <p>
* Calling this method to set this parameter is optional.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param type The image type of the thumbnail.
* @return Reference to this object.
*/
public Builder<T> imageType(int type)
{
updateStatus(Properties.IMAGE_TYPE, Status.ALREADY_SET);
imageType = type;
return this;
}
/**
* Sets the resizing scaling mode to use when creating the thumbnail.
* <p>
* Calling this method to set this parameter is optional.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param config The scaling mode to use.
* @return Reference to this object.
*/
public Builder<T> scalingMode(ScalingMode config)
{
checkForNull(config, "Scaling mode is null.");
updateStatus(Properties.SCALING_MODE, Status.ALREADY_SET);
updateStatus(Properties.RESIZER, Status.CANNOT_SET);
updateStatus(Properties.RESIZER_FACTORY, Status.CANNOT_SET);
scalingMode = config;
return this;
}
/**
* Sets the resizing operation to use when creating the thumbnail.
* <p>
* Calling this method to set this parameter is optional.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
* <p>
* This method cannot be called in conjunction with the
* {@link #resizerFactory(ResizerFactory)} method.
*
* @param resizer The scaling operation to use.
* @return Reference to this object.
*/
public Builder<T> resizer(Resizer resizer)
{
checkForNull(resizer, "Resizer is null.");
updateStatus(Properties.RESIZER, Status.ALREADY_SET);
updateStatus(Properties.RESIZER_FACTORY, Status.CANNOT_SET);
updateStatus(Properties.SCALING_MODE, Status.CANNOT_SET);
this.resizerFactory = new FixedResizerFactory(resizer);
return this;
}
/**
* Sets the {@link ResizerFactory} object to use to decide what kind of
* resizing operation is to be used when creating the thumbnail.
* <p>
* Calling this method to set this parameter is optional.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
* <p>
* This method cannot be called in conjunction with the
* {@link #resizer(Resizer)} method.
*
* @param resizerFactory The scaling operation to use.
* @return Reference to this object.
* @since 0.4.0
*/
public Builder<T> resizerFactory(ResizerFactory resizerFactory)
{
checkForNull(resizerFactory, "ResizerFactory is null.");
updateStatus(Properties.RESIZER_FACTORY, Status.ALREADY_SET);
updateStatus(Properties.RESIZER, Status.CANNOT_SET);
// disable the methods which set parameters for the Resizer
updateStatus(Properties.SCALING_MODE, Status.CANNOT_SET);
updateStatus(Properties.ALPHA_INTERPOLATION, Status.CANNOT_SET);
updateStatus(Properties.DITHERING, Status.CANNOT_SET);
updateStatus(Properties.ANTIALIASING, Status.CANNOT_SET);
updateStatus(Properties.RENDERING, Status.CANNOT_SET);
this.resizerFactory = resizerFactory;
return this;
}
/**
* Sets the alpha interpolation mode when performing the resizing
* operation to generate the thumbnail.
* <p>
* Calling this method to set this parameter is optional.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
* <p>
* This method cannot be called in conjunction with the
* {@link #resizerFactory(ResizerFactory)} method.
*
* @param config The alpha interpolation mode.
* @return Reference to this object.
*/
public Builder<T> alphaInterpolation(AlphaInterpolation config)
{
checkForNull(config, "Alpha interpolation is null.");
updateStatus(Properties.RESIZER_FACTORY, Status.CANNOT_SET);
updateStatus(Properties.ALPHA_INTERPOLATION, Status.ALREADY_SET);
alphaInterpolation = config;
return this;
}
/**
* Sets the dithering mode when performing the resizing
* operation to generate the thumbnail.
* <p>
* Calling this method to set this parameter is optional.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
* <p>
* This method cannot be called in conjunction with the
* {@link #resizerFactory(ResizerFactory)} method.
*
* @param config The dithering mode.
* @return Reference to this object.
*/
public Builder<T> dithering(Dithering config)
{
checkForNull(config, "Dithering is null.");
updateStatus(Properties.RESIZER_FACTORY, Status.CANNOT_SET);
updateStatus(Properties.DITHERING, Status.ALREADY_SET);
dithering = config;
return this;
}
/**
* Sets the antialiasing mode when performing the resizing
* operation to generate the thumbnail.
* <p>
* Calling this method to set this parameter is optional.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException}.
* <p>
* This method cannot be called in conjunction with the
* {@link #resizerFactory(ResizerFactory)} method.
*
* @param config The antialiasing mode.
* @return Reference to this object.
*/
public Builder<T> antialiasing(Antialiasing config)
{
checkForNull(config, "Antialiasing is null.");
updateStatus(Properties.RESIZER_FACTORY, Status.CANNOT_SET);
updateStatus(Properties.ANTIALIASING, Status.ALREADY_SET);
antialiasing = config;
return this;
}
/**
* Sets the rendering mode when performing the resizing
* operation to generate the thumbnail.
* <p>
* Calling this method to set this parameter is optional.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
* <p>
* This method cannot be called in conjunction with the
* {@link #resizerFactory(ResizerFactory)} method.
*
* @param config The rendering mode.
* @return Reference to this object.
*/
public Builder<T> rendering(Rendering config)
{
checkForNull(config, "Rendering is null.");
updateStatus(Properties.RESIZER_FACTORY, Status.CANNOT_SET);
updateStatus(Properties.RENDERING, Status.ALREADY_SET);
rendering = config;
return this;
}
/**
* Sets whether or not to keep the aspect ratio of the original image
* for the thumbnail.
* <p>
* Calling this method without first calling the {@link #size(int, int)}
* method will result in an {@link IllegalStateException} to be thrown.
* <p>
* If this method is not called when, by default the aspect ratio of
* the original image is preserved for the thumbnail.
* <p>
* Calling this method after calling the {@link #scale(double)} method
* or the {@link #scale(double, double)} method will result in a
* {@link IllegalStateException}.
*
* @param keep {@code true} if the thumbnail is to maintain
* the aspect ratio of the original image,
* {@code false} otherwise.
* @return Reference to this object.
*
* @throws IllegalStateException If
* <ol>
* <li>the {@link #size(int, int)} has
* not yet been called to specify the
* size of the thumbnail, or</li>
* <li>the {@link #scale(double)}
* method has been called, or</li>
* <li>the
* {@link #scale(double, double)}
* method has been called, or</li>
* <li>the {@link #width(int)} and/or
* {@link #height(int)} has been called
* and not preserving the aspect ratio
* is desired.</li>
* </ol>
*/
public Builder<T> keepAspectRatio(boolean keep)
{
if (statusMap.get(Properties.SCALE) == Status.ALREADY_SET)
{
throw new IllegalStateException("Cannot specify whether to " +
"keep the aspect ratio if the scaling factor has " +
"already been specified.");
}
if (statusMap.get(Properties.SIZE) == Status.NOT_READY)
{
throw new IllegalStateException("Cannot specify whether to " +
"keep the aspect ratio unless the size parameter has " +
"already been specified.");
}
if ((statusMap.get(Properties.WIDTH) == Status.ALREADY_SET ||
statusMap.get(Properties.HEIGHT) == Status.ALREADY_SET) &&
!keep
)
{
throw new IllegalStateException("The aspect ratio must be " +
"preserved when the width and/or height parameter " +
"has already been specified.");
}
updateStatus(Properties.KEEP_ASPECT_RATIO, Status.ALREADY_SET);
keepAspectRatio = keep;
return this;
}
/**
* Sets the output quality of the compression algorithm used to
* compress the thumbnail when it is written to an external destination
* such as a file or output stream.
* <p>
* The value is a {@code float} between {@code 0.0f} and {@code 1.0f}
* where {@code 0.0f} indicates the minimum quality and {@code 1.0f}
* indicates the maximum quality settings should be used for by the
* compression codec.
* <p>
* Calling this method to set this parameter is optional.
* <p>
* Calling this method in conjunction with {@link #asBufferedImage()}
* or {@link #asBufferedImages()} will not result in any changes to the
* final result.
* <p>
* Calling this method multiple times, or the
* {@link #outputQuality(double)} in conjunction with this method will
* result in an {@link IllegalStateException} to be thrown.
*
* @param quality The compression quality to use when writing
* the thumbnail.
* @return Reference to this object.
* @throws IllegalArgumentException If the argument is less than
* {@code 0.0f} or is greater than
* {@code 1.0f}.
*/
public Builder<T> outputQuality(float quality)
{
if (quality < 0.0f || quality > 1.0f)
{
throw new IllegalArgumentException(
"The quality setting must be in the range 0.0f and " +
"1.0f, inclusive."
);
}
updateStatus(Properties.OUTPUT_QUALITY, Status.ALREADY_SET);
outputQuality = quality;
return this;
}
/**
* Sets the output quality of the compression algorithm used to
* compress the thumbnail when it is written to an external destination
* such as a file or output stream.
* <p>
* The value is a {@code double} between {@code 0.0d} and {@code 1.0d}
* where {@code 0.0d} indicates the minimum quality and {@code 1.0d}
* indicates the maximum quality settings should be used for by the
* compression codec.
* <p>
* This method is a convenience method for {@link #outputQuality(float)}
* where the {@code double} argument type is accepted instead of a
* {@code float}.
* <p>
* Calling this method to set this parameter is optional.
* <p>
* Calling this method in conjunction with {@link #asBufferedImage()}
* or {@link #asBufferedImages()} will not result in any changes to the
* final result.
* <p>
* Calling this method multiple times, or the
* {@link #outputQuality(float)} in conjunction with this method will
* result in an {@link IllegalStateException} to be thrown.
*
* @param quality The compression quality to use when writing
* the thumbnail.
* @return Reference to this object.
* @throws IllegalArgumentException If the argument is less than
* {@code 0.0d} or is greater than
* {@code 1.0d}.
*/
public Builder<T> outputQuality(double quality)
{
if (quality < 0.0d || quality > 1.0d)
{
throw new IllegalArgumentException(
"The quality setting must be in the range 0.0d and " +
"1.0d, inclusive."
);
}
updateStatus(Properties.OUTPUT_QUALITY, Status.ALREADY_SET);
outputQuality = (float)quality;
if (outputQuality < 0.0f)
{
outputQuality = 0.0f;
}
else if (outputQuality > 1.0f)
{
outputQuality = 1.0f;
}
return this;
}
/**
* Sets the compression format to use when writing the thumbnail.
* <p>
* For example, to set the output format to JPEG, the following code
* can be used:
* <pre><code>
Thumbnails.of(image)
.size(640, 480)
.outputFormat("JPEG")
.toFile(thumbnail);
* </code></pre>
* or, alternatively:
* <pre><code>
Thumbnails.of(image)
.size(640, 480)
.outputFormat("jpg")
.toFile(thumbnail);
* </code></pre>
* <p>
* Currently, whether or not the compression format string is valid
* dependents on whether the Java Image I/O API recognizes the string
* as a format that it supports for output. (Valid format names can
* be obtained by calling the {@link ImageIO#getWriterFormatNames()}
* method.)
* <p>
* Calling this method to set this parameter is optional.
* <p>
* Calling this method in conjunction with {@link #asBufferedImage()}
* or {@link #asBufferedImages()} will not result in any changes to the
* final result.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param format The compression format to use when writing
* the thumbnail.
* @return Reference to this object.
* @throws IllegalArgumentException If an unsupported format is
* specified.
*/
public Builder<T> outputFormat(String format)
{
if (!ThumbnailatorUtils.isSupportedOutputFormat(format))
{
throw new IllegalArgumentException(
"Specified format is not supported: " + format
);
}
updateStatus(Properties.OUTPUT_FORMAT, Status.ALREADY_SET);
outputFormat = format;
return this;
}
/**
* Sets the compression format to use the same format as the original
* image.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @return Reference to this object.
* @since 0.4.0
*/
public Builder<T> useOriginalFormat()
{
updateStatus(Properties.OUTPUT_FORMAT, Status.ALREADY_SET);
outputFormat = ThumbnailParameter.ORIGINAL_FORMAT;
return this;
}
/**
* Sets whether or not to use the Exif metadata when orienting the
* thumbnail.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @param useExifOrientation {@code true} if the Exif metadata
* should be used to determine the
* orientation of the thumbnail,
* {@code false} otherwise.
* @return Reference to this object.
* @since 0.4.3
*/
public Builder<T> useExifOrientation(boolean useExifOrientation)
{
updateStatus(Properties.USE_EXIF_ORIENTATION, Status.ALREADY_SET);
this.useExifOrientation = useExifOrientation;
return this;
}
/**
* Indicates that the output format should be determined from the
* available information when writing the thumbnail image.
* <p>
* For example, calling this method will cause the output format to be
* determined from the file extension if thumbnails are written to
* files.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
*
* @return Reference to this object.
* @since 0.4.0
*/
public Builder<T> determineOutputFormat()
{
updateStatus(Properties.OUTPUT_FORMAT, Status.ALREADY_SET);
outputFormat = ThumbnailParameter.DETERMINE_FORMAT;
return this;
}
private boolean isOutputFormatNotSet()
{
return outputFormat == null || ThumbnailParameter.DETERMINE_FORMAT.equals(outputFormat);
}
/**
* Sets the compression format type of the thumbnail to write.
* <p>
* If the default type for the compression codec should be used, a
* value of {@link ThumbnailParameter#DEFAULT_FORMAT_TYPE} should be
* used.
* <p>
* Calling this method to set this parameter is optional.
* <p>
* Calling this method multiple times will result in an
* {@link IllegalStateException} to be thrown.
* <p>
* Furthermore, if this method is called, then calling the
* {@link #outputFormat} method is disabled, in order to prevent
* cases where the output format type does not exist in the format
* specified for the {@code outputFormat} method.
*
* @param formatType The compression format type
* @return Reference to this object.
* @throws IllegalArgumentException If an unsupported format type is
* specified for the current output
* format type. Or, if the output
* format has not been specified before
* this method was called.
*/
public Builder<T> outputFormatType(String formatType)
{
/*
* If the output format is the original format, and the format type
* is being specified, it's going to be likely that the specified
* type will not be present in all the formats, so we'll disallow
* it. (e.g. setting type to "JPEG", and if the original formats
* were JPEG and PNG, then we'd have a problem.
*/
if (formatType != ThumbnailParameter.DEFAULT_FORMAT_TYPE
&& isOutputFormatNotSet())
{
throw new IllegalArgumentException(
"Cannot set the format type if a specific output " +
"format has not been specified."
);
}
if (!ThumbnailatorUtils.isSupportedOutputFormatType(outputFormat, formatType))
{
throw new IllegalArgumentException(
"Specified format type (" + formatType + ") is not " +
" supported for the format: " + outputFormat
);
}
/*
* If the output format type is set, then we'd better make the
* output format unchangeable, or else we'd risk having a type
* that is not part of the output format.
*/
updateStatus(Properties.OUTPUT_FORMAT_TYPE, Status.ALREADY_SET);
if (!statusMap.containsKey(Properties.OUTPUT_FORMAT))
{
updateStatus(Properties.OUTPUT_FORMAT, Status.CANNOT_SET);
}
outputFormatType = formatType;
return this;
}
/**
* Sets the watermark to apply on the thumbnail.
* <p>
* This method can be called multiple times to apply multiple
* watermarks.
* <p>
* If multiple watermarks are to be applied, the watermarks will be
* applied in the order that this method is called.
* <p>
* Calling this method to set this parameter is optional.
*
* @param w The watermark to apply to the thumbnail.
* @return Reference to this object.
*/
public Builder<T> watermark(Watermark w)
{
if (w == null)
{
throw new NullPointerException("Watermark is null.");
}
filterPipeline.add(w);
return this;
}
/**
* Sets the image of the watermark to apply on the thumbnail.
* <p>
* This method is a convenience method for the
* {@link #watermark(Position, BufferedImage, float)} method, where
* the opacity is 50%, and the position is set to center of the
* thumbnail:
* <p>
* <pre>
watermark(Positions.CENTER, image, 0.5f);
* </pre>
* This method can be called multiple times to apply multiple
* watermarks.
* <p>
* If multiple watermarks are to be applied, the watermarks will be
* applied in the order that this method is called.
* <p>
* Calling this method to set this parameter is optional.
*
* @param image The image of the watermark.
* @return Reference to this object.
*/
public Builder<T> watermark(BufferedImage image)
{
return watermark(Positions.CENTER, image, 0.5f);
}
/**
* Sets the image and opacity of the watermark to apply on
* the thumbnail.
* <p>
* This method is a convenience method for the
* {@link #watermark(Position, BufferedImage, float)} method, where
* the opacity is 50%:
* <p>
* <pre>
watermark(Positions.CENTER, image, opacity);
* </pre>
* This method can be called multiple times to apply multiple
* watermarks.
* <p>
* If multiple watermarks are to be applied, the watermarks will be
* applied in the order that this method is called.
* <p>
* Calling this method to set this parameter is optional.
*
* @param image The image of the watermark.
* @param opacity The opacity of the watermark.
* <p>
* The value should be between {@code 0.0f} and
* {@code 1.0f}, where {@code 0.0f} is completely
* transparent, and {@code 1.0f} is completely
* opaque.
* @return Reference to this object.
*/
public Builder<T> watermark(BufferedImage image, float opacity)
{
return watermark(Positions.CENTER, image, opacity);
}
/**
* Sets the image and opacity and position of the watermark to apply on
* the thumbnail.
* <p>
* This method can be called multiple times to apply multiple
* watermarks.
* <p>
* If multiple watermarks are to be applied, the watermarks will be
* applied in the order that this method is called.
* <p>
* Calling this method to set this parameter is optional.
*
* @param position The position of the watermark.
* @param image The image of the watermark.
* @param opacity The opacity of the watermark.
* <p>
* The value should be between {@code 0.0f} and
* {@code 1.0f}, where {@code 0.0f} is completely
* transparent, and {@code 1.0f} is completely
* opaque.
* @return Reference to this object.
*/
public Builder<T> watermark(Position position, BufferedImage image, float opacity)
{
filterPipeline.add(new Watermark(position, image, opacity));
return this;
}
/*
* rotation
*/
/**
* Sets the amount of rotation to apply to the thumbnail.
* <p>
* The thumbnail will be rotated clockwise by the angle specified.
* <p>
* This method can be called multiple times to apply multiple
* rotations.
* <p>
* If multiple rotations are to be applied, the rotations will be
* applied in the order that this method is called.
* <p>
* Calling this method to set this parameter is optional.
*
* @param angle Angle in degrees.
* @return Reference to this object.
*/
public Builder<T> rotate(double angle)
{
filterPipeline.add(Rotation.newRotator(angle));
return this;
}
/*
* other filters
*/
/**
* Adds a {@link ImageFilter} to apply to the thumbnail.
* <p>
* This method can be called multiple times to apply multiple
* filters.
* <p>
* If multiple filters are to be applied, the filters will be
* applied in the order that this method is called.
* <p>
* Calling this method to set this parameter is optional.
*
* @param filter An image filter to apply to the thumbnail.
* @return Reference to this object.
*/
public Builder<T> addFilter(ImageFilter filter)
{
if (filter == null)
{
throw new NullPointerException("Filter is null.");
}
filterPipeline.add(filter);
return this;
}
/**
* Adds multiple {@link ImageFilter}s to apply to the thumbnail.
* <p>
* This method can be called multiple times to apply multiple
* filters.
* <p>
* If multiple filters are to be applied, the filters will be
* applied in the order that this method is called.
* <p>
* Calling this method to set this parameter is optional.
*
* @param filters A list of filters to apply to the thumbnail.
* @return Reference to this object.
*/
public Builder<T> addFilters(List<ImageFilter> filters)
{
if (filters == null)
{
throw new NullPointerException("Filters is null.");
}
filterPipeline.addAll(filters);
return this;
}
/**
* Checks whether the builder is ready to create thumbnails.
*
* @throws IllegalStateException If the builder is not ready to
* create thumbnails, due to some
* parameters not being set.
*/
private void checkReadiness()
{
for (Map.Entry<Properties, Status> s : statusMap.entrySet())
{
if (s.getValue() == Status.NOT_READY) {
throw new IllegalStateException(s.getKey().getName() +
" is not set.");
}
}
}
/**
* Returns a {@link Resizer} which is suitable for the current
* builder state.
*
* @param mode The scaling mode to use to create thumbnails.
* @return The {@link Resizer} which is suitable for the
* specified scaling mode and builder state.
*/
private Resizer makeResizer(ScalingMode mode)
{
Map<RenderingHints.Key, Object> hints =
new HashMap<RenderingHints.Key, Object>();
hints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, alphaInterpolation.getValue());
hints.put(RenderingHints.KEY_DITHERING, dithering.getValue());
hints.put(RenderingHints.KEY_ANTIALIASING, antialiasing.getValue());
hints.put(RenderingHints.KEY_RENDERING, rendering.getValue());
if (mode == ScalingMode.BILINEAR)
{
return new BilinearResizer(hints);
}
else if (mode == ScalingMode.BICUBIC)
{
return new BicubicResizer(hints);
}
else if (mode == ScalingMode.PROGRESSIVE_BILINEAR)
{
return new ProgressiveBilinearResizer(hints);
}
else
{
return new ProgressiveBilinearResizer(hints);
}
}
private void prepareResizerFactory()
{
/*
* If the scalingMode has been set, then use scalingMode to obtain
* a resizer, else, use the resizer field.
*/
if (statusMap.get(Properties.SCALING_MODE) == Status.ALREADY_SET)
{
this.resizerFactory =
new FixedResizerFactory(makeResizer(scalingMode));
}
}
/**
* Returns a {@link ThumbnailParameter} from the current builder state.
*
* @return A {@link ThumbnailParameter} from the current
* builder state.
*/
private ThumbnailParameter makeParam()
{
prepareResizerFactory();
int imageTypeToUse = imageType;
if (imageType == IMAGE_TYPE_UNSPECIFIED)
{
imageTypeToUse = ThumbnailParameter.ORIGINAL_IMAGE_TYPE;
}
/*
* croppingPosition being non-null means that a crop should
* take place.
*/
if (croppingPosition != null)
{
filterPipeline.addFirst(new Canvas(width, height, croppingPosition));
}
if (Double.isNaN(scaleWidth))
{
// If the dimensions were specified, do the following.
// Check that at least one dimension is specified.
// If it's not, it's a bug.
if (
width == DIMENSION_NOT_SPECIFIED &&
height == DIMENSION_NOT_SPECIFIED
)
{
throw new IllegalStateException(
"The width or height must be specified. If this " +
"exception is thrown, it is due to a bug in the " +
"Thumbnailator library."
);
}
// Set the unspecified dimension to a default value.
if (width == DIMENSION_NOT_SPECIFIED)
{
width = Integer.MAX_VALUE;
}
if (height == DIMENSION_NOT_SPECIFIED)
{
height = Integer.MAX_VALUE;
}
return new ThumbnailParameter(
new Dimension(width, height),
sourceRegion,
keepAspectRatio,
outputFormat,
outputFormatType,
outputQuality,
imageTypeToUse,
filterPipeline.getFilters(),
resizerFactory,
fitWithinDimenions,
useExifOrientation
);
}
else
{
// If the scaling factor was specified
return new ThumbnailParameter(
scaleWidth,
scaleHeight,
sourceRegion,
keepAspectRatio,
outputFormat,
outputFormatType,
outputQuality,
imageTypeToUse,
filterPipeline.getFilters(),
resizerFactory,
fitWithinDimenions,
useExifOrientation
);
}
}
/**
* Create the thumbnails and return as a {@link Iterable} of
* {@link BufferedImage}s.
* <p>
* For situations where multiple thumbnails are being generated, this
* method is preferred over the {@link #asBufferedImages()} method,
* as (1) the processing does not have to complete before the method
* returns and (2) the thumbnails can be retrieved one at a time,
* potentially reducing the number of thumbnails which need to be
* retained in the heap memory, potentially reducing the chance of
* {@link OutOfMemoryError}s from occurring.
* <p>
* If an {@link IOException} occurs during the processing of the
* thumbnail, the {@link Iterable} will return a {@code null} for that
* element.
*
* @return An {@link Iterable} which will provide an
* {@link Iterator} which returns thumbnails as
* {@link BufferedImage}s.
*/
public Iterable<BufferedImage> iterableBufferedImages()
{
checkReadiness();
/*
* TODO To get the precise error information, there would have to
* be an event notification mechanism.
*/
return new BufferedImageIterable();
}
/**
* Create the thumbnails and return as a {@link List} of
* {@link BufferedImage}s.
* <p>
* <h3>Note about performance</h3>
* If there are many thumbnails generated at once, it is possible that
* the Java virtual machine's heap space will run out and an
* {@link OutOfMemoryError} could result.
* <p>
* If many thumbnails are being processed at once, then using the
* {@link #iterableBufferedImages()} method would be preferable.
*
* @return A list of thumbnails.
* @throws IOException If an problem occurred during
* the reading of the original
* images.
*/
public List<BufferedImage> asBufferedImages() throws IOException
{
checkReadiness();
List<BufferedImage> thumbnails = new ArrayList<BufferedImage>();
// Create thumbnails
for (ImageSource<T> source : sources)
{
BufferedImageSink destination = new BufferedImageSink();
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<T, BufferedImage>(makeParam(), source, destination)
);
thumbnails.add(destination.getSink());
}
return thumbnails;
}
/**
* Creates a thumbnail and returns it as a {@link BufferedImage}.
* <p>
* To call this method, the thumbnail must have been created from a
* single source.
*
* @return A thumbnail as a {@link BufferedImage}.
* @throws IOException If an problem occurred during
* the reading of the original
* image.
* @throws IllegalArgumentException If multiple original images are
* specified.
*/
public BufferedImage asBufferedImage() throws IOException
{
checkReadiness();
Iterator<ImageSource<T>> iter = sources.iterator();
ImageSource<T> source = iter.next();
if (iter.hasNext())
{
throw new IllegalArgumentException("Cannot create one thumbnail from multiple original images.");
}
BufferedImageSink destination = new BufferedImageSink();
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<T, BufferedImage>(makeParam(), source, destination)
);
return destination.getSink();
}
/**
* Creates the thumbnails and stores them to the files, and returns
* a {@link List} of {@link File}s to the thumbnails.
* <p>
* When the destination file exists, and overwriting files has been
* disabled by calling the {@link #allowOverwrite(boolean)} method
* with {@code false}, then the thumbnail with the destination file
* already existing will not be written and the corresponding
* {@code File} object will not be included in the {@code List} returned
* by this method.
* <p>
* The file names for the thumbnails are obtained from the given
* {@link Iterable}.
*
* @param iterable An {@link Iterable} which returns an
* {@link Iterator} which returns file names
* which should be assigned to each thumbnail.
* @return A list of {@link File}s of the thumbnails
* which were created.
* @throws IOException If a problem occurs while reading the
* original images or writing the thumbnails
* to files.
* @since 0.3.7
*/
public List<File> asFiles(Iterable<File> iterable) throws IOException
{
checkReadiness();
if (iterable == null)
{
throw new NullPointerException("File name iterable is null.");
}
List<File> destinationFiles = new ArrayList<File>();
Iterator<File> filenameIter = iterable.iterator();
for (ImageSource<T> source : sources)
{
if (!filenameIter.hasNext())
{
throw new IndexOutOfBoundsException(
"Not enough file names provided by iterator."
);
}
ThumbnailParameter param = makeParam();
FileImageSink destination = new FileImageSink(filenameIter.next(), allowOverwrite);
try
{
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<T, File>(param, source, destination)
);
destinationFiles.add(destination.getSink());
}
catch (IllegalArgumentException e)
{
/*
* Handle the IllegalArgumentException which is thrown when
* the destination file already exists by not adding the
* current file to the destinationFiles list.
*/
}
}
return destinationFiles;
}
/**
* Creates the thumbnails and stores them to the files.
* <p>
* When the destination file exists, and overwriting files has been
* disabled by calling the {@link #allowOverwrite(boolean)} method
* with {@code false}, then the thumbnail with the destination file
* already existing will not be written.
* <p>
* The file names for the thumbnails are obtained from the given
* {@link Iterable}.
*
* @param iterable An {@link Iterable} which returns an
* {@link Iterator} which returns file names
* which should be assigned to each thumbnail.
* @throws IOException If a problem occurs while reading the
* original images or writing the thumbnails
* to files.
* @since 0.3.7
*/
public void toFiles(Iterable<File> iterable) throws IOException
{
asFiles(iterable);
}
/**
* Creates thumbnails and stores them to files using the
* {@link Rename} function to determine the filenames. The thubnail
* files are returned as a {@link List}.
* <p>
* When the destination file exists, and overwriting files has been
* disabled by calling the {@link #allowOverwrite(boolean)} method
* with {@code false}, then the thumbnail with the destination file
* already existing will not be written and the corresponding
* {@code File} object will not be included in the {@code List} returned
* by this method.
* <p>
* To call this method, the thumbnails must have been creates from
* files by calling the {@link Thumbnails#of(File...)} method.
*
* @param rename The rename function which is used to
* determine the filenames of the thumbnail
* files to write.
* @return A list of {@link File}s of the thumbnails
* which were created.
* @throws IOException If a problem occurs while reading the
* original images or writing the thumbnails
* to files.
* @throws IllegalStateException If the original images are not
* from files.
* @since 0.3.7
*/
public List<File> asFiles(Rename rename) throws IOException
{
return asFiles(null, rename);
}
/**
* Creates thumbnails and stores them to files in the directory
* specified by the given {@link File} object, and using the
* {@link Rename} function to determine the filenames. The thubnail
* files are returned as a {@link List}.
* <p>
* When the destination file exists, and overwriting files has been
* disabled by calling the {@link #allowOverwrite(boolean)} method
* with {@code false}, then the thumbnail with the destination file
* already existing will not be written and the corresponding
* {@code File} object will not be included in the {@code List} returned
* by this method.
* <p>
* Extra caution should be taken when using this method, as there are
* no protections in place to prevent file name collisions resulting
* from creating thumbnails from files in separate directories but
* having the same name. In such a case, the behavior will be depend
* on the behavior of the {@link #allowOverwrite(boolean)} as
* described in the previous paragraph.
* <p>
* To call this method, the thumbnails must have been creates from
* files by calling the {@link Thumbnails#of(File...)} method.
*
* @param destinationDir The destination directory to which the
* thumbnails should be written to.
* @param rename The rename function which is used to
* determine the filenames of the thumbnail
* files to write.
* @return A list of {@link File}s of the thumbnails
* which were created.
* @throws IOException If a problem occurs while reading the
* original images or writing the thumbnails
* to files.
* @throws IllegalStateException If the original images are not
* from files.
* @throws IllegalArgumentException If the destination directory
* is not a directory.
* @since 0.4.7
*/
public List<File> asFiles(File destinationDir, Rename rename) throws IOException
{
checkReadiness();
if (rename == null)
{
throw new NullPointerException("Rename is null.");
}
if (destinationDir != null && !destinationDir.isDirectory())
{
throw new IllegalArgumentException("Given destination is not a directory.");
}
List<File> destinationFiles = new ArrayList<File>();
for (ImageSource<T> source : sources)
{
if (!(source instanceof FileImageSource))
{
throw new IllegalStateException("Cannot create thumbnails to files if original images are not from files.");
}
ThumbnailParameter param = makeParam();
File f = ((FileImageSource)source).getSource();
File actualDestDir = destinationDir == null ? f.getParentFile() : destinationDir;
File destinationFile =
new File(actualDestDir, rename.apply(f.getName(), param));
FileImageSink destination = new FileImageSink(destinationFile, allowOverwrite);
try
{
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<T, File>(param, source, destination)
);
destinationFiles.add(destination.getSink());
}
catch (IllegalArgumentException e)
{
/*
* Handle the IllegalArgumentException which is thrown when
* the destination file already exists by not adding the
* current file to the destinationFiles list.
*/
}
}
return destinationFiles;
}
/**
* Creates thumbnails and stores them to files using the
* {@link Rename} function to determine the filenames.
* <p>
* When the destination file exists, and overwriting files has been
* disabled by calling the {@link #allowOverwrite(boolean)} method
* with {@code false}, then the thumbnail with the destination file
* already existing will not be written.
* <p>
* To call this method, the thumbnails must have been creates from
* files by calling the {@link Thumbnails#of(File...)} method.
*
* @param rename The rename function which is used to
* determine the filenames of the thumbnail
* files to write.
* @throws IOException If a problem occurs while reading the
* original images or writing the thumbnails
* to files.
* thumbnails to files.
* @throws IllegalStateException If the original images are not
* from files.
* @since 0.3.7
*/
public void toFiles(Rename rename) throws IOException
{
toFiles(null, rename);
}
/**
* Creates thumbnails and stores them to files in the directory
* specified by the given {@link File} object, and using the
* {@link Rename} function to determine the filenames.
* <p>
* When the destination file exists, and overwriting files has been
* disabled by calling the {@link #allowOverwrite(boolean)} method
* with {@code false}, then the thumbnail with the destination file
* already existing will not be written.
* <p>
* Extra caution should be taken when using this method, as there are
* no protections in place to prevent file name collisions resulting
* from creating thumbnails from files in separate directories but
* having the same name. In such a case, the behavior will be depend
* on the behavior of the {@link #allowOverwrite(boolean)} as
* described in the previous paragraph.
* <p>
* To call this method, the thumbnails must have been creates from
* files by calling the {@link Thumbnails#of(File...)} method.
*
* @param destinationDir The destination directory to which the
* thumbnails should be written to.
* @param rename The rename function which is used to
* determine the filenames of the thumbnail
* files to write.
* @throws IOException If a problem occurs while reading the
* original images or writing the thumbnails
* to files.
* thumbnails to files.
* @throws IllegalStateException If the original images are not
* from files.
* @throws IllegalArgumentException If the destination directory
* is not a directory.
* @since 0.4.7
*/
public void toFiles(File destinationDir, Rename rename) throws IOException
{
asFiles(destinationDir, rename);
}
/**
* Create a thumbnail and writes it to a {@link File}.
* <p>
* When the destination file exists, and overwriting files has been
* disabled by calling the {@link #allowOverwrite(boolean)} method
* with {@code false}, then an {@link IllegalArgumentException} will
* be thrown.
* <p>
* To call this method, the thumbnail must have been created from a
* single source.
*
* @param outFile The file to which the thumbnail is to be
* written to.
* @throws IOException If a problem occurs while reading the
* original images or writing the thumbnails
* to files.
* @throws IllegalArgumentException If multiple original image files
* are specified, or if the
* destination file exists, and
* overwriting files is disabled.
*/
public void toFile(File outFile) throws IOException
{
checkReadiness();
Iterator<ImageSource<T>> iter = sources.iterator();
ImageSource<T> source = iter.next();
if (iter.hasNext())
{
throw new IllegalArgumentException("Cannot output multiple thumbnails to one file.");
}
FileImageSink destination = new FileImageSink(outFile, allowOverwrite);
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<T, File>(makeParam(), source, destination)
);
}
/**
* Create a thumbnail and writes it to a {@link File}.
* <p>
* When the destination file exists, and overwriting files has been
* disabled by calling the {@link #allowOverwrite(boolean)} method
* with {@code false}, then an {@link IllegalArgumentException} will
* be thrown.
* <p>
* To call this method, the thumbnail must have been created from a
* single source.
*
* @param outFilepath The file to which the thumbnail is to be
* written to.
* @throws IOException If a problem occurs while reading the
* original images or writing the thumbnails
* to files.
* @throws IllegalArgumentException If multiple original image files
* are specified, or if the
* destination file exists, and
* overwriting files is disabled.
*/
public void toFile(String outFilepath) throws IOException
{
checkReadiness();
Iterator<ImageSource<T>> iter = sources.iterator();
ImageSource<T> source = iter.next();
if (iter.hasNext())
{
throw new IllegalArgumentException("Cannot output multiple thumbnails to one file.");
}
FileImageSink destination = new FileImageSink(outFilepath, allowOverwrite);
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<T, File>(makeParam(), source, destination)
);
}
/**
* Create a thumbnail and writes it to a {@link OutputStream}.
* <p>
* To call this method, the thumbnail must have been created from a
* single source.
*
* @param os The output stream to which the thumbnail
* is to be written to.
* @throws IOException If a problem occurs while reading the
* original images or writing the thumbnails.
* @throws IllegalArgumentException If multiple original image files
* are specified.
* @throws IllegalStateException If the output format has not
* been specified through the
* {@link #outputFormat(String)}
* method.
*/
public void toOutputStream(OutputStream os) throws IOException
{
checkReadiness();
Iterator<ImageSource<T>> iter = sources.iterator();
ImageSource<T> source = iter.next();
if (iter.hasNext())
{
throw new IllegalArgumentException("Cannot output multiple thumbnails to a single OutputStream.");
}
/*
* if the image is from a BufferedImage, then we require that the
* output format be set. (or else, we can't tell what format to
* output as!)
*/
if (source instanceof BufferedImageSource)
{
if (isOutputFormatNotSet())
{
throw new IllegalStateException(
"Output format not specified."
);
}
}
OutputStreamImageSink destination = new OutputStreamImageSink(os);
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<T, OutputStream>(makeParam(), source, destination)
);
}
/**
* Creates the thumbnails and writes them to {@link OutputStream}s
* provided by the {@link Iterable}.
*
* @param iterable An {@link Iterable} which returns an
* {@link Iterator} which returns the
* output stream which should be assigned to
* each thumbnail.
* @throws IOException If a problem occurs while reading the
* original images or writing the thumbnails.
* @throws IllegalStateException If the output format has not
* been specified through the
* {@link #outputFormat(String)}
* method.
*/
public void toOutputStreams(Iterable<? extends OutputStream> iterable) throws IOException
{
checkReadiness();
if (iterable == null)
{
throw new NullPointerException("OutputStream iterable is null.");
}
Iterator<? extends OutputStream> osIter = iterable.iterator();
for (ImageSource<T> source : sources)
{
/*
* if the image is from a BufferedImage, then we require that the
* output format be set. (or else, we can't tell what format to
* output as!)
*/
if (source instanceof BufferedImageSource)
{
if (isOutputFormatNotSet())
{
throw new IllegalStateException(
"Output format not specified."
);
}
}
if (!osIter.hasNext())
{
throw new IndexOutOfBoundsException(
"Not enough file names provided by iterator."
);
}
OutputStreamImageSink destination = new OutputStreamImageSink(osIter.next());
Thumbnailator.createThumbnail(
new SourceSinkThumbnailTask<T, OutputStream>(makeParam(), source, destination)
);
}
}
}
}
| Java |
/**
* This package contains classes which provide the core functionalities of
* Thumbnailator.
*/
package net.coobird.thumbnailator;
| Java |
package net.coobird.thumbnailator.tasks;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import net.coobird.thumbnailator.ThumbnailParameter;
import net.coobird.thumbnailator.tasks.io.FileImageSink;
import net.coobird.thumbnailator.tasks.io.FileImageSource;
/**
* A thumbnail generation task which reads and writes data from and to a
* {@link File}.
* <p>
* Only the first image included in the image file will be read. Subsequent
* images included in the image file will be ignored.
*
* @author coobird
*
*/
public class FileThumbnailTask extends ThumbnailTask<File, File>
{
/**
* The {@link SourceSinkThumbnailTask} used to perform the task.
*/
private final SourceSinkThumbnailTask<File, File> task;
/**
* Creates a {@link ThumbnailTask} in which image data is read from the
* specified {@link File} and is output to a specified {@link File}, using
* the parameters provided in the specified {@link ThumbnailParameter}.
*
* @param param The parameters to use to create the thumbnail.
* @param sourceFile The {@link File} from which image data is read.
* @param destinationFile The {@link File} to which thumbnail is written.
* @throws NullPointerException If the parameter is {@code null}.
*/
public FileThumbnailTask(ThumbnailParameter param, File sourceFile, File destinationFile)
{
super(param);
this.task = new SourceSinkThumbnailTask<File, File>(
param,
new FileImageSource(sourceFile),
new FileImageSink(destinationFile)
);
}
@Override
public BufferedImage read() throws IOException
{
return task.read();
}
@Override
public void write(BufferedImage img) throws IOException
{
task.write(img);
}
@Override
public ThumbnailParameter getParam()
{
return task.getParam();
}
@Override
public File getSource()
{
return task.getSource();
}
@Override
public File getDestination()
{
return task.getDestination();
}
}
| Java |
package net.coobird.thumbnailator.tasks;
import java.io.IOException;
/**
* An exception used to indicate that the specified format could not be
* used in an operation.
*
* @author coobird
*
*/
public class UnsupportedFormatException extends IOException
{
/**
* An ID used for serialization.
*/
private static final long serialVersionUID = 1254432584303852552L;
/**
* The format name which was not supported.
*/
private final String formatName;
/**
* A constant which is used to indicate an unknown format.
*/
public static final String UNKNOWN = "<unknown>";
/**
* Instantiates a {@link UnsupportedFormatException} with the unsupported
* format.
*
* @param formatName Format name.
*/
public UnsupportedFormatException(String formatName)
{
super();
this.formatName = formatName;
}
/**
* Instantiates a {@link UnsupportedFormatException} with the unsupported
* format and a detailed message.
*
* @param formatName Format name.
* @param s A message detailing the exception.
*/
public UnsupportedFormatException(String formatName, String s)
{
super(s);
this.formatName = formatName;
}
/**
* Returns the format name which is not supported.
*
* @return Format name.
*/
public String getFormatName()
{
return formatName;
}
}
| Java |
/**
* This package provides classes which perform image input and output
* operations, which can be used to aid in creating and writing thumbnails
* to and from external sources.
*/
package net.coobird.thumbnailator.tasks;
| Java |
package net.coobird.thumbnailator.tasks;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import net.coobird.thumbnailator.ThumbnailParameter;
import net.coobird.thumbnailator.tasks.io.InputStreamImageSource;
import net.coobird.thumbnailator.tasks.io.OutputStreamImageSink;
/**
* A thumbnail generation task which streams data from an {@link InputStream}
* to an {@link OutputStream}.
* <p>
* This class does not close the {@link InputStream} and {@link OutputStream}
* upon the completion of processing.
* <p>
* Only the first image obtained from the data stream will be read. Subsequent
* images will be ignored.
*
* @author coobird
*
*/
public class StreamThumbnailTask extends ThumbnailTask<InputStream, OutputStream>
{
/**
* The {@link SourceSinkThumbnailTask} used to perform the task.
*/
private final SourceSinkThumbnailTask<InputStream, OutputStream> task;
/**
* Creates a {@link ThumbnailTask} in which streamed image data from the
* specified {@link InputStream} is output to a specified
* {@link OutputStream}, using the parameters provided in the specified
* {@link ThumbnailParameter}.
*
* @param param The parameters to use to create the thumbnail.
* @param is The {@link InputStream} from which to obtain image data.
* @param os The {@link OutputStream} to send thumbnail data to.
* @throws NullPointerException If the parameter is {@code null}.
*/
public StreamThumbnailTask(ThumbnailParameter param, InputStream is, OutputStream os)
{
super(param);
this.task = new SourceSinkThumbnailTask<InputStream, OutputStream>(
param,
new InputStreamImageSource(is),
new OutputStreamImageSink(os)
);
}
@Override
public BufferedImage read() throws IOException
{
return task.read();
}
@Override
public void write(BufferedImage img) throws IOException
{
task.write(img);
}
@Override
public ThumbnailParameter getParam()
{
return task.getParam();
}
@Override
public InputStream getSource()
{
return task.getSource();
}
@Override
public OutputStream getDestination()
{
return task.getDestination();
}
}
| Java |
package net.coobird.thumbnailator.tasks;
import java.awt.image.BufferedImage;
import java.io.IOException;
import net.coobird.thumbnailator.ThumbnailParameter;
import net.coobird.thumbnailator.tasks.io.ImageSink;
import net.coobird.thumbnailator.tasks.io.ImageSource;
/**
* A {@link ThumbnailTask} which holds an {@link ImageSource} from which the
* image is read or retrieved, and an {@link ImageSink} to which the thumbnail
* is stored or written.
* <p>
* This class will take care of handing off information from the
* {@link ImageSource} to the {@link ImageSink}. For example, the output format
* that should be used by the {@link ImageSink} will be handed off if the
* {@link ThumbnailParameter#ORIGINAL_FORMAT} parameter is set.
*
* @author coobird
*
* @param <S> The source class from which the source image is retrieved
* or read.
* @param <D> The destination class to which the thumbnail is stored
* or written.
*/
public class SourceSinkThumbnailTask<S, D> extends ThumbnailTask<S, D>
{
/**
* The source from which the image is retrieved or read.
*/
private final ImageSource<S> source;
/**
* The destination to which the thumbnail is stored or written.
*/
private final ImageSink<D> destination;
/**
* Creates a {@link ThumbnailTask} in which an image is retrived from the
* specified {@link ImageSource} and written to the specified
* {@link ImageSink}, using the parameters provided in the specified
* {@link ThumbnailParameter}.
*
* @param param The parameters to use to create the thumbnail.
* @param source The source from which the image is retrieved
* or read from.
* @param destination The destination to which the thumbnail is
* stored or written to.
* @throws NullPointerException If either the parameter,
* {@link ImageSource} or {@link ImageSink}
* is {@code null}.
*/
public SourceSinkThumbnailTask(ThumbnailParameter param, ImageSource<S> source, ImageSink<D> destination)
{
super(param);
if (source == null)
{
throw new NullPointerException("ImageSource cannot be null.");
}
if (destination == null)
{
throw new NullPointerException("ImageSink cannot be null.");
}
source.setThumbnailParameter(param);
this.source = source;
destination.setThumbnailParameter(param);
this.destination = destination;
}
@Override
public BufferedImage read() throws IOException
{
BufferedImage img = source.read();
inputFormatName = source.getInputFormatName();
return img;
}
@Override
public void write(BufferedImage img) throws IOException
{
String paramOutputFormat = param.getOutputFormat();
String formatName = null;
if (ThumbnailParameter.DETERMINE_FORMAT.equals(paramOutputFormat))
{
paramOutputFormat = destination.preferredOutputFormatName();
}
if (paramOutputFormat == ThumbnailParameter.ORIGINAL_FORMAT)
{
formatName = inputFormatName;
}
else
{
formatName = paramOutputFormat;
}
destination.setOutputFormatName(formatName);
destination.write(img);
}
@Override
public S getSource()
{
return source.getSource();
}
@Override
public D getDestination()
{
return destination.getSink();
}
}
| Java |
package net.coobird.thumbnailator.tasks;
import java.awt.image.BufferedImage;
import java.io.IOException;
import net.coobird.thumbnailator.ThumbnailParameter;
/**
* This class is used by {@link ThumbnailTask} implementations which is used
* when creating thumbnails from external sources and destinations.
* <p>
* If the image handled by a {@link ThumbnailTask} contains multiple images,
* only the first image will be read by the {@link #read()} method. Any
* subsequent images will be ignored.
*
* @param <S> The class from which the image is retrieved or read.
* @param <D> The class to which the thumbnail is stored or written.
*
* @author coobird
*
*/
public abstract class ThumbnailTask<S, D>
{
/**
* The parameters to use when creating a thumbnail.
*/
protected final ThumbnailParameter param;
/**
* String indicating the image format of the input image.
* <p>
* To be used for situtions where the output image format should be the
* same as the input image format.
*/
protected String inputFormatName;
/**
* Constant used to obtain the first image when reading an image file.
*/
protected static final int FIRST_IMAGE_INDEX = 0;
/**
* Instantiates a {@link ThumbnailTask} with the parameters to use when
* creating thumbnails.
*
* @param param The parameters to use when creating thumbnails.
* @throws NullPointerException If the parameter is {@code null}.
*/
protected ThumbnailTask(ThumbnailParameter param)
{
if (param == null)
{
throw new NullPointerException("The parameter is null.");
}
this.param = param;
}
/**
* Reads a source image.
*
* @return The image which was obtained from the source.
* @throws IOException Thrown when an I/O problem occurs when reading
* from the image source.
*/
/*
* Future changes note: The public interface of this method may have to be
* changed to support reading images tile-by-tile. This change may be
* required in order to support large images.
*/
public abstract BufferedImage read() throws IOException;
/**
* Writes the thumbnail to the destination.
*
* @param img The image to write.
* @throws UnsupportedFormatException When an image file which is to be
* read or written is unsupported.
* @throws IOException Thrown when an I/O problem occurs when writing the
* image.
*/
public abstract void write(BufferedImage img) throws IOException;
/**
* Returns the {@link ThumbnailParameter} for this {@link ThumbnailTask},
* used when performing a thumbnail generation operation.
*
* @return The parameters to use when generating thumbnails.
*/
public ThumbnailParameter getParam()
{
return param;
}
/**
* Returns the source from which the source image is retrieved or read.
*
* @return The source.
*/
public abstract S getSource();
/**
* Returns the destination to which the thumbnail is stored or written.
*
* @return The destination.
*/
public abstract D getDestination();
}
| Java |
package net.coobird.thumbnailator.tasks.io;
import net.coobird.thumbnailator.ThumbnailParameter;
/**
* An abstract class for {@link ImageSource}s.
*
* @author coobird
*
*/
public abstract class AbstractImageSource<T> implements ImageSource<T>
{
/**
* The image format of the input image.
*/
protected String inputFormatName;
/**
* The parameters that should be used when retrieving the image.
*/
protected ThumbnailParameter param;
/**
* Indicates whether the input has already been read.
*/
protected boolean hasReadInput = false;
/**
* Default constructor.
*/
protected AbstractImageSource() {}
/**
* Indicates that the {@link ImageSource} has completed reading the input
* file, and returns the value given in the argument.
* <p>
* This method should be used by implementation classes when returning
* the result of the {@link #read()} method, as shown in the following
* example code:
<pre>
return finishedReading(sourceImage);
</pre>
*
* @param <V> The return value type.
* @param returnValue The return value of the {@link #read()} method.
* @return The return value of the {@link #read()} method.
*/
protected <V> V finishedReading(V returnValue)
{
hasReadInput = true;
return returnValue;
}
public void setThumbnailParameter(ThumbnailParameter param)
{
this.param = param;
}
public String getInputFormatName()
{
if (!hasReadInput)
{
throw new IllegalStateException("Input has not been read yet.");
}
return inputFormatName;
}
}
| Java |
package net.coobird.thumbnailator.tasks.io;
import java.awt.image.BufferedImage;
import java.io.IOException;
/**
* An {@link ImageSink} which stores the resulting thumbnail to a
* {@link BufferedImage}.
*
* @author coobird
*
*/
public class BufferedImageSink extends AbstractImageSink<BufferedImage>
{
/**
* The {@link BufferedImage} which holds the thumbnail.
*/
private BufferedImage img;
/**
* Indicates whether the thumbnail has been written to this object.
*/
private boolean written = false;
public void write(BufferedImage img) throws IOException
{
super.write(img);
this.img = img;
written = true;
}
/**
* Returns the thumbnail.
*
* @return The thumbnail.
* @throws IllegalStateException If a thumbnail has not been stored to
* this {@link BufferedImageSink} yet.
*/
public BufferedImage getSink()
{
if (!written)
{
throw new IllegalStateException("BufferedImageSink has not been written to yet.");
}
return img;
}
@Override
public void setOutputFormatName(String format)
{
// do nothing
}
}
| Java |
package net.coobird.thumbnailator.tasks.io;
import java.awt.image.BufferedImage;
import java.io.IOException;
import net.coobird.thumbnailator.ThumbnailParameter;
/**
* An abstract class for {@link ImageSink}s.
*
* @author coobird
*
*/
public abstract class AbstractImageSink<T> implements ImageSink<T>
{
/**
* The name of the format to output the image as.
*/
protected String outputFormat;
/**
* The parameters that should be used when storing the image.
*/
protected ThumbnailParameter param;
/**
* Default constructor.
*/
protected AbstractImageSink() {}
public void setOutputFormatName(String format)
{
outputFormat = format;
}
public void setThumbnailParameter(ThumbnailParameter param)
{
this.param = param;
}
public void write(BufferedImage img) throws IOException
{
if (img == null)
{
throw new NullPointerException("Cannot write a null image.");
}
if (ThumbnailParameter.DETERMINE_FORMAT.equals(outputFormat))
{
outputFormat = preferredOutputFormatName();
}
}
public String preferredOutputFormatName()
{
return ThumbnailParameter.ORIGINAL_FORMAT;
}
}
| Java |
package net.coobird.thumbnailator.tasks.io;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import net.coobird.thumbnailator.ThumbnailParameter;
import net.coobird.thumbnailator.tasks.UnsupportedFormatException;
import net.coobird.thumbnailator.util.BufferedImages;
import net.coobird.thumbnailator.util.ThumbnailatorUtils;
/**
* An {@link ImageSink} which specifies an {@link OutputStream} to which the
* thumbnail image should be written to.
*
* @author coobird
*
*/
public class OutputStreamImageSink extends AbstractImageSink<OutputStream>
{
/**
* The {@link OutputStream} to which the thumbnail image is to be
* written to.
*/
private final OutputStream os;
/**
* Instantiates an {@link OutputStreamImageSink} with the
* {@link OutputStream} to which the thumbnail should be written to.
*
* @param os The {@link OutputStream} to write the thumbnail to.
* @throws NullPointerException If the {@link OutputStream} is
* {@code null}.
*/
public OutputStreamImageSink(OutputStream os)
{
super();
if (os == null)
{
throw new NullPointerException("OutputStream cannot be null.");
}
this.os = os;
}
/**
* Writes the resulting image to the {@link OutputStream}.
*
* @param img The image to write.
* @throws UnsupportedFormatException When an unsupported format has been
* specified by the
* {@link #setOutputFormatName(String)}
* method.
* @throws IOException When a problem occurs while writing
* the image.
* @throws NullPointerException If the image is {@code null}.
* @throws IllegalStateException If the output format has not been set
* by calling the
* {@link #setOutputFormatName(String)}
* method.
*/
public void write(BufferedImage img) throws IOException
{
super.write(img);
if (outputFormat == null)
{
throw new IllegalStateException("Output format has not been set.");
}
String formatName = outputFormat;
Iterator<ImageWriter> writers =
ImageIO.getImageWritersByFormatName(formatName);
if (!writers.hasNext())
{
throw new UnsupportedFormatException(
formatName,
"No suitable ImageWriter found for " + formatName + "."
);
}
ImageWriter writer = writers.next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
if (writeParam.canWriteCompressed() && param != null)
{
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
/*
* Sets the compression format type, if specified.
*
* Note:
* The value to denote that the codec's default compression type
* should be used is null.
*/
if (param.getOutputFormatType() != ThumbnailParameter.DEFAULT_FORMAT_TYPE)
{
writeParam.setCompressionType(param.getOutputFormatType());
}
else
{
List<String> supportedFormats =
ThumbnailatorUtils.getSupportedOutputFormatTypes(formatName);
if (!supportedFormats.isEmpty())
{
writeParam.setCompressionType(supportedFormats.get(0));
}
}
/*
* Sets the compression quality, if specified.
*
* Note:
* The value to denote that the codec's default compression quality
* should be used is Float.NaN.
*/
if (!Float.isNaN(param.getOutputQuality()))
{
writeParam.setCompressionQuality(param.getOutputQuality());
}
}
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
if (ios == null)
{
throw new IOException("Could not open OutputStream.");
}
/*
* Note:
* The following code is a workaround for the JPEG writer which ships
* with the JDK.
*
* At issue is, that the JPEG writer appears to write the alpha
* channel when it should not. To circumvent this, images which are
* to be saved as a JPEG will be copied to another BufferedImage without
* an alpha channel before it is saved.
*
* Also, the BMP writer appears not to support ARGB, so an RGB image
* will be produced before saving.
*/
if (
formatName.equalsIgnoreCase("jpg")
|| formatName.equalsIgnoreCase("jpeg")
|| formatName.equalsIgnoreCase("bmp")
)
{
img = BufferedImages.copy(img, BufferedImage.TYPE_INT_RGB);
}
writer.setOutput(ios);
writer.write(null, new IIOImage(img, null, null), writeParam);
/*
* Dispose the writer to free resources.
*
* This seems to be the main culprit of `OutOfMemoryError`s which
* started to frequently appear with Java 7 Update 21.
*
* Issue:
* http://code.google.com/p/thumbnailator/issues/detail?id=42
*/
writer.dispose();
ios.close();
}
public OutputStream getSink()
{
return os;
}
}
| Java |
package net.coobird.thumbnailator.tasks.io;
import java.awt.image.BufferedImage;
import java.io.IOException;
import net.coobird.thumbnailator.ThumbnailParameter;
/**
* An interface to be implemented by classes which read or retrieve images
* from which a thumbnail should be produced.
*
* @param <T> The source class from which the source image is retrieved
* or read.
* @author coobird
*
*/
public interface ImageSource<T>
{
/**
* Retrieves the image from the source.
*
* @return The image.
* @throws IOException When a problem occurs while reading or obtaining
* the image.
*/
public BufferedImage read() throws IOException;
/**
* Returns the name of the image format.
*
* @return The image format name. If there is no
* image format information, then
* {@code null} will be returned.
* @throws IllegalStateException If the source image has not been
* read yet.
*/
public String getInputFormatName();
/**
* Sets the {@link ThumbnailParameter} from which to retrieve parameters
* to use when retrieving the image.
*
* @param param The {@link ThumbnailParameter} with image
* reading parameters.
*/
public void setThumbnailParameter(ThumbnailParameter param);
/**
* Returns the source from which the image is read or retrieved.
*
* @return The source of the image.
*/
public T getSource();
}
| Java |
/**
* This package provides classes which perform image input and output
* operations in conjunction with the
* {@link net.coobird.thumbnailator.tasks.SourceSinkThumbnailTask} class.
*/
package net.coobird.thumbnailator.tasks.io;
| Java |
package net.coobird.thumbnailator.tasks.io;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import net.coobird.thumbnailator.geometry.Region;
/**
* An {@link ImageSource} which uses a {@link BufferedImage} as the source
* image.
*
* @author coobird
*
*/
public class BufferedImageSource extends AbstractImageSource<BufferedImage>
{
/**
* The image that should be used as the source for making a thumbnail.
*/
private final BufferedImage img;
/**
* Instantiates a {@link BufferedImageSource} object with the
* {@link BufferedImage} that should be used as the source image for making
* thumbnails.
*
* @param img The source image.
* @throws NullPointerException If the image is null.
*/
public BufferedImageSource(BufferedImage img)
{
super();
if (img == null)
{
throw new NullPointerException("Image cannot be null.");
}
this.img = img;
}
public BufferedImage read() throws IOException
{
inputFormatName = null;
if (param != null && param.getSourceRegion() != null)
{
Region region = param.getSourceRegion();
Rectangle r = region.calculate(img.getWidth(), img.getHeight());
return finishedReading(img.getSubimage(r.x, r.y, r.width, r.height));
}
else
{
return finishedReading(img);
}
}
public BufferedImage getSource()
{
return img;
}
}
| Java |
package net.coobird.thumbnailator.tasks.io;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import net.coobird.thumbnailator.filters.ImageFilter;
import net.coobird.thumbnailator.geometry.Region;
import net.coobird.thumbnailator.tasks.UnsupportedFormatException;
import net.coobird.thumbnailator.util.exif.ExifFilterUtils;
import net.coobird.thumbnailator.util.exif.ExifUtils;
import net.coobird.thumbnailator.util.exif.Orientation;
/**
* An {@link ImageSource} which reads the source image from a file.
*
* @author coobird
*
*/
public class FileImageSource extends AbstractImageSource<File>
{
/**
* The index used to obtain the first image in an image file.
*/
private static final int FIRST_IMAGE_INDEX = 0;
/**
* The file from which the image should be obtained.
*/
private final File sourceFile;
/**
* Instantiates a {@link FileImageSource} with the specified file as
* the source image.
*
* @param sourceFile The source image file.
* @throws NullPointerException If the image is null.
*/
public FileImageSource(File sourceFile)
{
super();
if (sourceFile == null)
{
throw new NullPointerException("File cannot be null.");
}
this.sourceFile = sourceFile;
}
/**
* Instantiates a {@link FileImageSource} with the specified file as
* the source image.
*
* @param sourceFilePath The filepath of the source image file.
* @throws NullPointerException If the image is null.
*/
public FileImageSource(String sourceFilePath)
{
super();
if (sourceFilePath == null)
{
throw new NullPointerException("File cannot be null.");
}
this.sourceFile = new File(sourceFilePath);
}
public BufferedImage read() throws IOException
{
if (!sourceFile.exists())
{
throw new FileNotFoundException(
"Could not find file: " + sourceFile.getAbsolutePath()
);
}
/* TODO refactor.
* The following code has been adapted from the
* StreamThumbnailTask.read method.
*/
ImageInputStream iis = ImageIO.createImageInputStream(sourceFile);
if (iis == null)
{
throw new IOException(
"Could not open file: " + sourceFile.getAbsolutePath());
}
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (!readers.hasNext())
{
String sourcePath = sourceFile.getPath();
throw new UnsupportedFormatException(
UnsupportedFormatException.UNKNOWN,
"No suitable ImageReader found for " + sourcePath + "."
);
}
ImageReader reader = readers.next();
reader.setInput(iis);
inputFormatName = reader.getFormatName();
try
{
if (param.useExifOrientation())
{
Orientation orientation;
orientation =
ExifUtils.getExifOrientation(reader, FIRST_IMAGE_INDEX);
// Skip this code block if there's no rotation needed.
if (orientation != null && orientation != Orientation.TOP_LEFT)
{
List<ImageFilter> filters = param.getImageFilters();
// EXIF orientation filter is added to the beginning, as
// it should be performed early to prevent mis-orientation
// in later filters.
filters.add(0, ExifFilterUtils.getFilterForOrientation(orientation));
}
}
}
catch (Exception e)
{
// If something goes wrong, then skip the orientation-related
// processing.
// TODO Ought to have some way to track errors.
}
BufferedImage img;
if (param != null && param.getSourceRegion() != null)
{
Region region = param.getSourceRegion();
int width = reader.getWidth(FIRST_IMAGE_INDEX);
int height = reader.getHeight(FIRST_IMAGE_INDEX);
Rectangle sourceRegion = region.calculate(width, height);
ImageReadParam irParam = reader.getDefaultReadParam();
irParam.setSourceRegion(sourceRegion);
img = reader.read(FIRST_IMAGE_INDEX, irParam);
}
else
{
img = reader.read(FIRST_IMAGE_INDEX);
}
/*
* Dispose the reader to free resources.
*
* This seems to be one of the culprits which was causing
* `OutOfMemoryError`s which began appearing frequently with
* Java 7 Update 21.
*
* Issue:
* http://code.google.com/p/thumbnailator/issues/detail?id=42
*/
reader.dispose();
iis.close();
return finishedReading(img);
}
/**
* Returns the source file from which an image is read.
*
* @return The {@code File} representation of the source file.
*/
public File getSource()
{
return sourceFile;
}
}
| Java |
package net.coobird.thumbnailator.tasks.io;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
/**
* An {@link ImageSource} which retrieves a source image from a URL.
*
* @author coobird
*
*/
public class URLImageSource extends AbstractImageSource<URL>
{
/**
* The URL from which to retrieve the source image.
*/
private final URL url;
/**
* The proxy to use to connect to the image URL.
* <p>
* If a proxy is not required, then this field will be {@code null}.
*/
private final Proxy proxy;
/**
* Instantiates an {@link URLImageSource} with the URL from which the
* source image should be retrieved from.
*
* @param url URL to the source image.
* @throws NullPointerException If the URL is null
*/
public URLImageSource(URL url)
{
super();
if (url == null)
{
throw new NullPointerException("URL cannot be null.");
}
this.url = url;
this.proxy = null;
}
/**
* Instantiates an {@link URLImageSource} with the URL from which the
* source image should be retrieved from.
*
* @param url URL to the source image.
* @throws NullPointerException If the URL is null
* @throws MalformedURLException If the URL is not valid.
*/
public URLImageSource(String url) throws MalformedURLException
{
super();
if (url == null)
{
throw new NullPointerException("URL cannot be null.");
}
this.url = new URL(url);
this.proxy = null;
}
/**
* Instantiates an {@link URLImageSource} with the URL from which the
* source image should be retrieved from, along with the proxy to use
* to connect to the aforementioned URL.
*
* @param url URL to the source image.
* @param proxy Proxy to use to connect to the URL.
* @throws NullPointerException If the URL and or the proxy is null
*/
public URLImageSource(URL url, Proxy proxy)
{
super();
if (url == null)
{
throw new NullPointerException("URL cannot be null.");
}
else if (proxy == null)
{
throw new NullPointerException("Proxy cannot be null.");
}
this.url = url;
this.proxy = proxy;
}
/**
* Instantiates an {@link URLImageSource} with the URL from which the
* source image should be retrieved from, along with the proxy to use
* to connect to the aforementioned URL.
*
* @param url URL to the source image.
* @param proxy Proxy to use to connect to the URL.
* @throws NullPointerException If the URL and or the proxy is null
* @throws MalformedURLException If the URL is not valid.
*/
public URLImageSource(String url, Proxy proxy) throws MalformedURLException
{
super();
if (url == null)
{
throw new NullPointerException("URL cannot be null.");
}
else if (proxy == null)
{
throw new NullPointerException("Proxy cannot be null.");
}
this.url = new URL(url);
this.proxy = proxy;
}
public BufferedImage read() throws IOException
{
InputStreamImageSource source;
try
{
if (proxy != null)
{
source = new InputStreamImageSource(url.openConnection(proxy).getInputStream());
}
else
{
source = new InputStreamImageSource(url.openStream());
}
}
catch (IOException e)
{
throw new IOException("Could not open connection to URL: " + url);
}
source.setThumbnailParameter(param);
BufferedImage img;
try
{
img = source.read();
}
catch (Exception e)
{
throw new IOException("Could not obtain image from URL: " + url);
}
this.inputFormatName = source.getInputFormatName();
return finishedReading(img);
}
/**
* Returns the URL from which the source image is retrieved from.
*
* @return the url The URL to the source image.s
*/
public URL getSource()
{
return url;
}
/**
* Returns the proxy to use when connecting to the URL to retrieve the
* source image.
*
* @return the proxy The proxy used to connect to a URL.
*/
public Proxy getProxy()
{
return proxy;
}
}
| Java |
package net.coobird.thumbnailator.tasks.io;
import java.awt.image.BufferedImage;
import java.io.IOException;
import net.coobird.thumbnailator.ThumbnailParameter;
/**
* An interface to be implemented by classes which stores the image resulting
* from a thumbnail generation task.
*
* @param <T> The destination class to which the thumbnail is stored
* or written.
*
* @author coobird
*
*/
public interface ImageSink<T>
{
/**
* Writes the resulting image to a destination.
*
* @param img The image to write or store.
* @throws IOException When a problem occurs while writing or storing
* the image.
* @throws NullPointerException If the image is {@code null}.
*/
public void write(BufferedImage img) throws IOException;
/**
* Sets the output format of the resulting image.
* <p>
* For {@link ImageSink}s which stores raw images, the format name specified
* by this method may be ignored.
*
* @param format File format with which to store the image.
*/
public void setOutputFormatName(String format);
/**
* Sets the {@link ThumbnailParameter} from which to retrieve parameters
* to use when storing the image.
*
* @param param The {@link ThumbnailParameter} with image
* writing parameters.
*/
public void setThumbnailParameter(ThumbnailParameter param);
/**
* Returns the output format to use from information provided for the
* output image.
* <p>
* If the output format cannot be determined, then
* {@link ThumbnailParameter#ORIGINAL_FORMAT} should be returned.
*/
public String preferredOutputFormatName();
/**
* Returns the destination to which the thumbnail will be stored or
* written.
*
* @return The destination for the thumbnail image.
*/
public T getSink();
}
| Java |
package net.coobird.thumbnailator.tasks.io;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import net.coobird.thumbnailator.ThumbnailParameter;
import net.coobird.thumbnailator.tasks.UnsupportedFormatException;
import net.coobird.thumbnailator.util.BufferedImages;
import net.coobird.thumbnailator.util.ThumbnailatorUtils;
/**
* An {@link ImageSink} which writes the resulting thumbnail to a file.
* <p>
* Under certain circumstances, the destination file can change in the course
* of processing.
* <p>
* This can occur in cases where the file extension does not
* match the output format set by the {@link #setOutputFormatName(String)}
* method. In this case, the file name will have a file extension corresponding
* to the output format set in the above method to be appended to the file
* name originally provided when instantiating the {@link FileImageSink} object.
*
* @author coobird
*
*/
public class FileImageSink extends AbstractImageSink<File>
{
/**
* The file to which the thumbnail is written to.
* <p>
* Under certain circumstances, the {@link File} object can be replaced
* in the course of processing. This can occur in cases where the file
* extension has been changed due to incongruence between the extension
* and the desired output format.
*/
private File destinationFile;
private final boolean allowOverwrite;
/**
* Instantiates a {@link FileImageSink} with the file to which the thumbnail
* should be written to.
* <p>
* The output format to use will be determined from the file extension.
* If another format should be used, then the
* {@link #setOutputFormatName(String)} should be called with the desired
* output format name.
* <p>
* When the destination file exists, then this {@code FileImageSink} will
* overwrite the existing file.
*
* @param destinationFile The destination file.
* @throws NullPointerException If the specified file is {@code null}.
*/
public FileImageSink(File destinationFile)
{
this(destinationFile, true);
}
/**
* Instantiates a {@link FileImageSink} with the file to which the thumbnail
* should be written to.
* <p>
* The output format to use will be determined from the file extension.
* If another format should be used, then the
* {@link #setOutputFormatName(String)} should be called with the desired
* output format name.
*
* @param destinationFile The destination file.
* @param allowOverwrite Whether or not the {@code FileImageSink}
* should overwrite the destination file if
* it already exists.
* @throws NullPointerException If the specified file is {@code null}.
*/
public FileImageSink(File destinationFile, boolean allowOverwrite)
{
super();
if (destinationFile == null)
{
throw new NullPointerException("File cannot be null.");
}
this.destinationFile = destinationFile;
this.outputFormat = getExtension(destinationFile);
this.allowOverwrite = allowOverwrite;
}
/**
* Instantiates a {@link FileImageSink} with the file to which the thumbnail
* should be written to.
* <p>
* The output format to use will be determined from the file extension.
* If another format should be used, then the
* {@link #setOutputFormatName(String)} should be called with the desired
* output format name.
* <p>
* When the destination file exists, then this {@code FileImageSink} will
* overwrite the existing file.
*
* @param destinationFilePath The destination file path.
* @throws NullPointerException If the specified file path is {@code null}.
*/
public FileImageSink(String destinationFilePath)
{
this(destinationFilePath, true);
}
/**
* Instantiates a {@link FileImageSink} with the file to which the thumbnail
* should be written to.
* <p>
* The output format to use will be determined from the file extension.
* If another format should be used, then the
* {@link #setOutputFormatName(String)} should be called with the desired
* output format name.
*
* @param destinationFilePath The destination file path.
* @param allowOverwrite Whether or not the {@code FileImageSink}
* should overwrite the destination file if
* it already exists.
* @throws NullPointerException If the specified file path is {@code null}.
*/
public FileImageSink(String destinationFilePath, boolean allowOverwrite)
{
super();
if (destinationFilePath == null)
{
throw new NullPointerException("File cannot be null.");
}
this.destinationFile = new File(destinationFilePath);
this.outputFormat = getExtension(destinationFile);
this.allowOverwrite = allowOverwrite;
}
/**
* Determines whether an specified format name and file extension are
* for the same format.
*
* @param formatName Format name.
* @param fileExtension File extension.
* @return Returns {@code true} if the specified file
* extension is valid for the specified format.
*/
private static boolean isMatchingFormat(String formatName, String fileExtension)
{
if (formatName == null || fileExtension == null)
{
return false;
}
ImageWriter iw;
try
{
iw = ImageIO.getImageWritersByFormatName(formatName).next();
}
catch (NoSuchElementException e)
{
return false;
}
String[] suffixes = iw.getOriginatingProvider().getFileSuffixes();
for (String suffix : suffixes)
{
if (fileExtension.equalsIgnoreCase(suffix))
{
return true;
}
}
return false;
}
/**
* Returns the file extension of the given {@link File}.
*
* @param f The file.
* @return The extension of the file.
*/
private static String getExtension(File f)
{
String fileName = f.getName();
if (
fileName.indexOf('.') != -1
&& fileName.lastIndexOf('.') != fileName.length() - 1
)
{
int lastIndex = fileName.lastIndexOf('.');
return fileName.substring(lastIndex + 1);
}
return null;
}
@Override
public String preferredOutputFormatName()
{
String fileExtension = getExtension(destinationFile);
if (fileExtension != null)
{
Iterator<ImageReader> rIter = ImageIO.getImageReadersBySuffix(fileExtension);
if (rIter.hasNext())
{
try
{
return rIter.next().getFormatName();
}
catch (IOException e)
{
return ThumbnailParameter.ORIGINAL_FORMAT;
}
}
}
return outputFormat;
}
/**
* Writes the resulting image to a file.
*
* @param img The image to write.
* @throws UnsupportedFormatException When an unsupported format has been
* specified by the
* {@link #setOutputFormatName(String)}
* method, or if the output format
* has not been set and cannot be
* determined from the file name.
* @throws IOException When a problem occurs while writing
* the image.
* @throws NullPointerException If the image is {@code null}.
* @throws IllegalArgumentException If this {@code FileImageSink} does
* not permit overwriting the
* destination file and the destination
* file already exists.
*/
public void write(BufferedImage img) throws IOException
{
super.write(img);
/* TODO refactor.
* The following code has been adapted from the
* StreamThumbnailTask.write method.
*/
/*
* Add or replace the file extension of the output file.
*
* If the file extension matches the output format's extension,
* then leave as is.
*
* Else, append the extension for the output format to the filename.
*/
String fileExtension = getExtension(destinationFile);
String formatName = outputFormat;
if (formatName != null && (fileExtension == null || !isMatchingFormat(formatName, fileExtension)))
{
destinationFile = new File(destinationFile.getAbsolutePath() + "." + formatName);
}
if (!allowOverwrite && destinationFile.exists()) {
throw new IllegalArgumentException("The destination file exists.");
}
/*
* If a formatName is not specified, then attempt to determine it from
* the file extension.
*/
if (formatName == null && fileExtension != null)
{
Iterator<ImageReader> rIter = ImageIO.getImageReadersBySuffix(fileExtension);
if (rIter.hasNext())
{
formatName = rIter.next().getFormatName();
}
}
if (formatName == null)
{
throw new UnsupportedFormatException(
formatName,
"Could not determine output format."
);
}
// Checks for available writers for the format.
Iterator<ImageWriter> writers =
ImageIO.getImageWritersByFormatName(formatName);
if (!writers.hasNext())
{
throw new UnsupportedFormatException(
formatName,
"No suitable ImageWriter found for " + formatName + "."
);
}
ImageWriter writer = writers.next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
if (writeParam.canWriteCompressed() && param != null)
{
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
/*
* Sets the compression format type, if specified.
*
* Note:
* The value to denote that the codec's default compression type
* should be used is null.
*/
if (param.getOutputFormatType() != ThumbnailParameter.DEFAULT_FORMAT_TYPE)
{
writeParam.setCompressionType(param.getOutputFormatType());
}
else
{
List<String> supportedFormats =
ThumbnailatorUtils.getSupportedOutputFormatTypes(formatName);
if (!supportedFormats.isEmpty())
{
writeParam.setCompressionType(supportedFormats.get(0));
}
}
/*
* Sets the compression quality, if specified.
*
* Note:
* The value to denote that the codec's default compression quality
* should be used is Float.NaN.
*/
if (!Float.isNaN(param.getOutputQuality()))
{
writeParam.setCompressionQuality(param.getOutputQuality());
}
}
/*
* Here, an explicit FileOutputStream is being created, as using a
* File object directly to obtain an ImageOutputStream was causing
* a problem where if the destination file already exists, then the
* image data was being written to the beginning of the file rather than
* creating a new file.
*/
ImageOutputStream ios;
FileOutputStream fos;
/*
* The following two lines used to be surrounded by a try-catch,
* but it has been removed, as the IOException which it was
* throwing in the catch block was not giving good feedback as to
* what was causing the original IOException.
*
* It would have been informative to have the IOException which
* caused this problem, but the IOException in Java 5 does not
* have a "cause" parameter.
*
* The "cause" parameter has been introduced in Java 6:
* http://docs.oracle.com/javase/6/docs/api/java/io/IOException.html#IOException%28java.lang.String,%20java.lang.Throwable%29
*
* TODO Whether to surround this portion of code in a try-catch
* again is debatable, as it wouldn't really add more utility.
*
* Furthermore, there are other calls in this method which will
* throw IOExceptions, but they are not surrounded by try-catch
* blocks. (A similar example exists in the OutputStreamImageSink
* where the ImageIO.createImageOutputStream is not surrounded
* in a try-catch.)
*
* Related issue:
* http://code.google.com/p/thumbnailator/issues/detail?id=37
*/
fos = new FileOutputStream(destinationFile);
ios = ImageIO.createImageOutputStream(fos);
if (ios == null || fos == null)
{
throw new IOException("Could not open output file.");
}
/*
* Note:
* The following code is a workaround for the JPEG writer which ships
* with the JDK.
*
* At issue is, that the JPEG writer appears to write the alpha
* channel when it should not. To circumvent this, images which are
* to be saved as a JPEG will be copied to another BufferedImage without
* an alpha channel before it is saved.
*
* Also, the BMP writer appears not to support ARGB, so an RGB image
* will be produced before saving.
*/
if (
formatName.equalsIgnoreCase("jpg")
|| formatName.equalsIgnoreCase("jpeg")
|| formatName.equalsIgnoreCase("bmp")
)
{
img = BufferedImages.copy(img, BufferedImage.TYPE_INT_RGB);
}
writer.setOutput(ios);
writer.write(null, new IIOImage(img, null, null), writeParam);
/*
* Dispose the writer to free resources.
*
* This seems to be the main culprit of `OutOfMemoryError`s which
* started to frequently appear with Java 7 Update 21.
*
* Issue:
* http://code.google.com/p/thumbnailator/issues/detail?id=42
*/
writer.dispose();
ios.close();
fos.close();
}
/**
* Returns the detination file of the thumbnail image.
* <p>
* If the final destination of the thumbnail changes in the course of
* writing the thumbnail. (For example, if the file extension for the given
* destination did not match the destination file format, then the correct
* file extension could be appended.)
*
* @return the destinationFile
*/
public File getSink()
{
return destinationFile;
}
}
| Java |
package net.coobird.thumbnailator.tasks.io;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import net.coobird.thumbnailator.filters.ImageFilter;
import net.coobird.thumbnailator.geometry.Region;
import net.coobird.thumbnailator.tasks.UnsupportedFormatException;
import net.coobird.thumbnailator.util.exif.ExifFilterUtils;
import net.coobird.thumbnailator.util.exif.ExifUtils;
import net.coobird.thumbnailator.util.exif.Orientation;
/**
* An {@link ImageSource} which uses an {@link InputStream} to read the
* source image.
*
* @author coobird
*
*/
public class InputStreamImageSource extends AbstractImageSource<InputStream>
{
/**
* The index used to obtain the first image in an image file.
*/
private static final int FIRST_IMAGE_INDEX = 0;
/**
* The {@link InputStream} from which the source image is to be read.
*/
private final InputStream is;
/**
* Instantiates an {@link InputStreamImageSource} with the
* {@link InputStream} which will be used to read the source image.
*
* @param is The {@link InputStream} which is to be used to obtain
* the source image.
* @throws NullPointerException If the {@link InputStream} is
* {@code null}.
*/
public InputStreamImageSource(InputStream is)
{
super();
if (is == null)
{
throw new NullPointerException("InputStream cannot be null.");
}
this.is = is;
}
public BufferedImage read() throws IOException
{
ImageInputStream iis = ImageIO.createImageInputStream(is);
if (iis == null)
{
throw new IOException("Could not open InputStream.");
}
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
if (!readers.hasNext())
{
throw new UnsupportedFormatException(
UnsupportedFormatException.UNKNOWN,
"No suitable ImageReader found for source data."
);
}
ImageReader reader = readers.next();
reader.setInput(iis);
inputFormatName = reader.getFormatName();
try
{
if (param.useExifOrientation())
{
Orientation orientation;
orientation =
ExifUtils.getExifOrientation(reader, FIRST_IMAGE_INDEX);
// Skip this code block if there's no rotation needed.
if (orientation != null && orientation != Orientation.TOP_LEFT)
{
List<ImageFilter> filters = param.getImageFilters();
// EXIF orientation filter is added to the beginning, as
// it should be performed early to prevent mis-orientation
// in later filters.
filters.add(0, ExifFilterUtils.getFilterForOrientation(orientation));
}
}
}
catch (Exception e)
{
// If something goes wrong, then skip the orientation-related
// processing.
// TODO Ought to have some way to track errors.
}
BufferedImage img;
if (param != null && param.getSourceRegion() != null)
{
Region region = param.getSourceRegion();
int width = reader.getWidth(FIRST_IMAGE_INDEX);
int height = reader.getHeight(FIRST_IMAGE_INDEX);
Rectangle sourceRegion = region.calculate(width, height);
ImageReadParam irParam = reader.getDefaultReadParam();
irParam.setSourceRegion(sourceRegion);
img = reader.read(FIRST_IMAGE_INDEX, irParam);
}
else
{
img = reader.read(FIRST_IMAGE_INDEX);
}
/*
* Dispose the reader to free resources.
*
* This seems to be one of the culprits which was causing
* `OutOfMemoryError`s which began appearing frequently with
* Java 7 Update 21.
*
* Issue:
* http://code.google.com/p/thumbnailator/issues/detail?id=42
*/
reader.dispose();
iis.close();
return finishedReading(img);
}
public InputStream getSource()
{
return is;
}
}
| Java |
package net.coobird.thumbnailator.resizers;
import java.awt.Dimension;
/**
* This interface is implemented by all classes which will return a
* {@link Resizer} that should be used when creating a thumbnail.
*
* @author coobird
* @since 0.4.0
*
*/
public interface ResizerFactory
{
/**
* Returns the default {@link Resizer}.
*
* @return The default {@code Resizer}.
*/
public Resizer getResizer();
/**
* Returns a suitable {@link Resizer}, given the {@link Dimension}s of the
* original image and the thumbnail image.
*
* @param originalSize The size of the original image.
* @param thumbnailSize The size of the thumbnail.
* @return The suitable {@code Resizer} to perform the
* resizing operation for the given condition.
*/
public Resizer getResizer(Dimension originalSize, Dimension thumbnailSize);
}
| Java |
package net.coobird.thumbnailator.resizers;
import java.awt.Graphics;
import java.awt.RenderingHints;
import java.awt.RenderingHints.Key;
import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.Map;
/**
* A {@link Resizer} which does not actually resize the image.
* <p>
* The source image will be drawn at the origin of the destination image.
*
* @author coobird
* @since 0.4.0
*
*/
public class NullResizer extends AbstractResizer
{
/**
* Instantiates the {@code NullResizer} which draws the source image at
* the origin of the destination image.
*/
public NullResizer()
{
this(
RenderingHints.VALUE_INTERPOLATION_BILINEAR,
Collections.<Key, Object>emptyMap()
);
}
/**
* This constructor is {@code private} to prevent the rendering hints
* from being set, as this {@link Resizer} does not perform any resizing.
*
* @param interpolationValue Not used.
* @param hints Not used.
*/
private NullResizer(Object interpolationValue, Map<Key, Object> hints)
{
super(interpolationValue, hints);
}
public void resize(BufferedImage srcImage, BufferedImage destImage)
{
super.performChecks(srcImage, destImage);
Graphics g = destImage.getGraphics();
g.drawImage(srcImage, 0, 0, null);
g.dispose();
}
}
| Java |
/**
*
*/
package net.coobird.thumbnailator.resizers.configurations;
import java.awt.RenderingHints;
import java.awt.RenderingHints.Key;
/**
* An enum which is used to specify the alpha interpolation settings of the
* resizing operations.
*
* @author coobird
*
*/
public enum AlphaInterpolation implements ResizerConfiguration
{
/**
* A hint used to emphasize speed when performing alpha interpolation.
*/
SPEED(RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED),
/**
* A hint used to emphasize quality when performing alpha interpolation.
*/
QUALITY(RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY),
/**
* A hint which indicates to use the default alpha interpolation settings.
*/
DEFAULT(RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT),
;
/**
* The field used to hold the rendering hint.
*/
private final Object value;
/**
* Instantiates this enum.
*
* @param value The rendering hint value.
*/
private AlphaInterpolation(Object value)
{
this.value = value;
}
public Key getKey()
{
return RenderingHints.KEY_ALPHA_INTERPOLATION;
}
public Object getValue()
{
return value;
}
} | Java |
/**
* This package provides enums which are used to set rendering hints used when
* using {@link net.coobird.thumbnailator.resizers.Resizers} to create
* thumbnails.
*/
package net.coobird.thumbnailator.resizers.configurations;
| Java |
package net.coobird.thumbnailator.resizers.configurations;
import java.awt.RenderingHints;
import net.coobird.thumbnailator.resizers.Resizer;
/**
* An interface which are implemented by classes and enums which provide
* configuration information for {@link Resizer}s.
*
* @author coobird
*
*/
public interface ResizerConfiguration
{
/**
* Returns a rendering hint key.
*
* @return Rendering hint key.
*/
public RenderingHints.Key getKey();
/**
* Returns a rendering hint value.
*
* @return Rendering hint value.
*/
public Object getValue();
}
| Java |
/**
*
*/
package net.coobird.thumbnailator.resizers.configurations;
import java.awt.RenderingHints;
import java.awt.RenderingHints.Key;
/**
* An enum which is used to specify the antialiasing settings of the
* resizing operations.
*
* @author coobird
*
*/
public enum Antialiasing implements ResizerConfiguration
{
/**
* A hint to enable antialiasing.
*/
ON(RenderingHints.VALUE_ANTIALIAS_ON),
/**
* A hint to disable antialiasing.
*/
OFF(RenderingHints.VALUE_ANTIALIAS_OFF),
/**
* A hint to use the default antialiasing settings.
*/
DEFAULT(RenderingHints.VALUE_ANTIALIAS_DEFAULT),
;
/**
* The field used to hold the rendering hint.
*/
private final Object value;
/**
* Instantiates this enum.
*
* @param value The rendering hint value.
*/
private Antialiasing(Object value)
{
this.value = value;
}
public Key getKey()
{
return RenderingHints.KEY_ANTIALIASING;
}
public Object getValue()
{
return value;
}
} | Java |
/**
*
*/
package net.coobird.thumbnailator.resizers.configurations;
import java.awt.RenderingHints;
import java.awt.RenderingHints.Key;
/**
* An enum which is used to specify the dithering settings of the
* resizing operations.
*
* @author coobird
*
*/
public enum Dithering implements ResizerConfiguration
{
/**
* A hint used to enable dithering.
*/
ENABLE(RenderingHints.VALUE_DITHER_ENABLE),
/**
* A hint used to disable dithering.
*/
DISABLE(RenderingHints.VALUE_DITHER_DISABLE),
/**
* A hint to use the default dithering settings.
*/
DEFAULT(RenderingHints.VALUE_DITHER_DEFAULT),
;
/**
* The field used to hold the rendering hint.
*/
private final Object value;
/**
* Instantiates this enum.
*
* @param value The rendering hint value.
*/
private Dithering(Object value)
{
this.value = value;
}
public Key getKey()
{
return RenderingHints.KEY_DITHERING;
}
public Object getValue()
{
return value;
}
}
| Java |
/**
*
*/
package net.coobird.thumbnailator.resizers.configurations;
import java.awt.RenderingHints;
import java.awt.RenderingHints.Key;
/**
* An enum which is used to specify the dithering settings of the
* resizing operations.
*
* @author coobird
*
*/
public enum Rendering implements ResizerConfiguration
{
/**
* A hint used to emphasize speed when rendering.
*/
SPEED(RenderingHints.VALUE_RENDER_SPEED),
/**
* A hint used to emphasize quality when rendering.
*/
QUALITY(RenderingHints.VALUE_RENDER_QUALITY),
/**
* A hint to use the default rendering settings.
*/
DEFAULT(RenderingHints.VALUE_RENDER_DEFAULT),
;
/**
*
*/
private final Object value;
/**
* @param value
*/
private Rendering(Object value)
{
this.value = value;
}
public Key getKey()
{
return RenderingHints.KEY_ALPHA_INTERPOLATION;
}
public Object getValue()
{
return value;
}
} | Java |
/**
*
*/
package net.coobird.thumbnailator.resizers.configurations;
import net.coobird.thumbnailator.resizers.ProgressiveBilinearResizer;
/**
* An enum which is used to specify how to scale images when creating
* thumbnails.
*
* @author coobird
*
*/
public enum ScalingMode
{
/**
* A hint to use bilinear interpolation when resizing images.
*/
BILINEAR,
/**
* A hint to use bicubic interpolation when resizing images.
*/
BICUBIC,
/**
* A hint to use progressing bilinear interpolation when resizing images.
* <p>
* For details on this technique, refer to the documentation of the
* {@link ProgressiveBilinearResizer} class.
*/
PROGRESSIVE_BILINEAR,
;
}
| Java |
package net.coobird.thumbnailator.resizers;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.Map;
/**
* A {@link Resizer} which performs resizing operations by using
* progressive bilinear scaling.
* <p>
* The resizing technique used in this class is based on the technique
* discussed in <em>Chapter 4: Images</em> of
* <a href="http://filthyrichclients.org">Filthy Rich Clients</a>
* by Chet Haase and Romain Guy.
* <p>
* The actual implemenation of the technique is independent of the code which
* is provided in the book.
*
* @author coobird
*
*/
public class ProgressiveBilinearResizer extends AbstractResizer
{
/**
* Instantiates a {@link ProgressiveBilinearResizer} with default
* rendering hints.
*/
public ProgressiveBilinearResizer()
{
this(Collections.<RenderingHints.Key, Object>emptyMap());
}
/**
* Instantiates a {@link ProgressiveBilinearResizer} with the specified
* rendering hints.
*
* @param hints Additional rendering hints to apply.
*/
public ProgressiveBilinearResizer(Map<RenderingHints.Key, Object> hints)
{
super(RenderingHints.VALUE_INTERPOLATION_BILINEAR, hints);
}
/**
* Resizes an image using the progressive bilinear scaling technique.
* <p>
* If the source and/or destination image is {@code null}, then a
* {@link NullPointerException} will be thrown.
*
* @param srcImage The source image.
* @param destImage The destination image.
*
* @throws NullPointerException When the source and/or the destination
* image is {@code null}.
*/
@Override
public void resize(BufferedImage srcImage, BufferedImage destImage)
throws NullPointerException
{
super.performChecks(srcImage, destImage);
int currentWidth = srcImage.getWidth();
int currentHeight = srcImage.getHeight();
final int targetWidth = destImage.getWidth();
final int targetHeight = destImage.getHeight();
// If multi-step downscaling is not required, perform one-step.
if ((targetWidth * 2 >= currentWidth) && (targetHeight * 2 >= currentHeight))
{
Graphics2D g = destImage.createGraphics();
g.drawImage(srcImage, 0, 0, targetWidth, targetHeight, null);
g.dispose();
return;
}
// Temporary image used for in-place resizing of image.
BufferedImage tempImage = new BufferedImage(
currentWidth,
currentHeight,
destImage.getType()
);
Graphics2D g = tempImage.createGraphics();
g.setRenderingHints(RENDERING_HINTS);
g.setComposite(AlphaComposite.Src);
/*
* Determine the size of the first resize step should be.
* 1) Beginning from the target size
* 2) Increase each dimension by 2
* 3) Until reaching the original size
*/
int startWidth = targetWidth;
int startHeight = targetHeight;
while (startWidth < currentWidth && startHeight < currentHeight)
{
startWidth *= 2;
startHeight *= 2;
}
currentWidth = startWidth / 2;
currentHeight = startHeight / 2;
// Perform first resize step.
g.drawImage(srcImage, 0, 0, currentWidth, currentHeight, null);
// Perform an in-place progressive bilinear resize.
while ( (currentWidth >= targetWidth * 2) && (currentHeight >= targetHeight * 2) )
{
currentWidth /= 2;
currentHeight /= 2;
if (currentWidth < targetWidth)
{
currentWidth = targetWidth;
}
if (currentHeight < targetHeight)
{
currentHeight = targetHeight;
}
g.drawImage(
tempImage,
0, 0, currentWidth, currentHeight,
0, 0, currentWidth * 2, currentHeight * 2,
null
);
}
g.dispose();
// Draw the resized image onto the destination image.
Graphics2D destg = destImage.createGraphics();
destg.drawImage(tempImage, 0, 0, targetWidth, targetHeight, 0, 0, currentWidth, currentHeight, null);
destg.dispose();
}
}
| Java |
package net.coobird.thumbnailator.resizers;
import java.awt.Dimension;
/**
* A {@link ResizerFactory} that returns a specific {@link Resizer}
* unconditionally.
*
* @author coobird
* @since 0.4.0
*/
public class FixedResizerFactory implements ResizerFactory
{
/**
* The resizer which is to be returned unconditionally by this class.
*/
private final Resizer resizer;
/**
* Creates an instance of the {@link FixedResizerFactory} which returns
* the speicifed {@link Resizer} under all circumstances.
*
* @param resizer The {@link Resizer} instance that is to be returned
* under all circumstances.
*/
public FixedResizerFactory(Resizer resizer)
{
this.resizer = resizer;
}
public Resizer getResizer()
{
return resizer;
}
public Resizer getResizer(Dimension originalSize, Dimension thumbnailSize)
{
return resizer;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.