Crop(cut) image as a paint - image

As the title i said, i want to cut a region of image (say left bottom corner), but after i cut this area, i want this area to be white as a "Paint" tool to cut image.
I could crop the image by using the code below, but in this code i just put the image where i cut it into a new image file.
public Crop() {
super();
ImageIcon icon = new ImageIcon("C:/TEMP/chest.jpg");
image = icon.getImage();
image = createImage(new FilteredImageSource(image.getSource(),
new CropImageFilter(0, 515, 250, 250)));
ImageIcon icon2= new ImageIcon(image);
BufferedImage bufferedImage = new BufferedImage(icon2.getIconWidth(),
icon2.getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
graphics.drawImage(image, 0, 0, null);
File newFile = new File("C:/TEMP/chest-new.jpg");
try {
ImageIO.write(bufferedImage, "jpg", newFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
super.paint(g);
if (insets == null) {
insets = getInsets();
}
g.drawImage(image, insets.left, insets.top, this);
}
public static void main(String args[]) {
JFrame f = new Crop();
f.setSize(250, 250);
f.show();
}
}
What do i want is i want the area that is cut become to "white", and original image.
As a image link below:
An image after cut

Related

Downloading images from Parse

I am working on a project that uses a parse server. It works like tinder and allows users to download and display names and images of other users nearby.
It works, accept for one bug where the names and the images do not match up correctly when displayed in the app.
The app initially downloads and creates an array of local users, and this works fine.
I then download their images using the following code:
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereWithinKilometers("location", parseCustLocation, searchRadius);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(final List<ParseUser> objects, ParseException e) {
if (e==null){
Log.d("state", "215 query successful");
if (objects.size()>0) {
for (final ParseUser user : objects){
Log.d("state", "231"+user.getUsername());
//TextView text = (TextView) findViewById(R.id.Name);
Users.add(user);
sUsers.add((String) user.get("Name"));
locations.add((ParseGeoPoint) user.get("location"));
parseFiles.add((ParseFile) user.get("image"));
}
for (ParseFile file : parseFiles) {
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e==null){
Log.d("state", "174 we've got data");
Bitmap bmp = BitmapFactory.decodeByteArray(data,0,data.length);
bitmaps.add(bmp);
if (sUsers.size()==bitmaps.size()){
swipeAdapter.updateData(sUsers,bitmaps);
}
}
}
});}
As far as I can tell, I think the issue is with the lines
Bitmap bmp = BitmapFactory.decodeByteArray(data,0,data.length);
bitmaps.add(bmp);
as, for example, when I run the debugger I have two arrays as follows (the bitmapFactory seems to be putting the bitmaps in any part of the bitmap[]):
sUsers[0] = "Billy",
sUsers[1] = "Sarah",
sUsers[2] = "Jim",
bitmaps[0] = Sarahs image,
bitmaps[1] = Jims image,
bitmaps[2] = Billys image
When obviously I need
bitmaps[0] = Billys image,
bitmaps[1] = Sarahs image,
bitmaps[2] = Jims image,
NOTE:
The bitmaps seem to be in the correct order if I run the app step by step using the debugger.
file.getDataInBackground is an async callback, so the first data retrieved will be the first added to bitmaps array,
You can use an Hashmap each key will be the user objectId and the key the data of your user.
Map<String, data> map = new HashMap<String, data>(); // your Hashmap
Thanks Julien, I managed to get it working correctly but with a very crude workaround using lots of nested Async tasks:
parseFiles.get(0).getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e==null){
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
bitmaps.add(0, bmp);
parseFiles.get(1).getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e==null){
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
bitmaps.add(1, bmp);
parseFiles.get(2).getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e==null){
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
bitmaps.add(2, bmp);
parseFiles.get(3).getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e==null){
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
bitmaps.add(3, bmp);
parseFiles.get(4).getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e==null){
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
bitmaps.add(4, bmp);
parseFiles.get(5).getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e==null){
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
//bitmaps.add(bmp);
bitmaps.add(5, bmp);
if (sVenueUsers.size()==bitmaps.size()){
swipeAdapter.updateData(sUsers, bitmaps);
}
}
}
});
}
}
});
}
}
});
}
}
});
}
}
});
}
}
});
I tried your Hashmap idea, but got the message that data was an unrecognised class. I shall try working it through later.

Extract Images from PDF coordinates using iText

I found some examples for how to extract images from PDF using iText. But what I am looking for is to get the images from PDF by coordinates.
Is it possible? If yes then how it can be done.
Along the lines of the iText example ExtractImages you can extract code like this:
PdfReader reader = new PdfReader(resourceStream);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
ImageRenderListener listener = new ImageRenderListener("testpdf");
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
parser.processContent(i, listener);
}
The ImageRenderListener is defined like this:
class ImageRenderListener implements RenderListener
{
final String name;
int counter = 100000;
public ImageRenderListener(String name)
{
this.name = name;
}
public void beginTextBlock() { }
public void renderText(TextRenderInfo renderInfo) { }
public void endTextBlock() { }
public void renderImage(ImageRenderInfo renderInfo)
{
try
{
PdfImageObject image = renderInfo.getImage();
if (image == null) return;
int number = renderInfo.getRef() != null ? renderInfo.getRef().getNumber() : counter++;
String filename = String.format("%s-%s.%s", name, number, image.getFileType());
FileOutputStream os = new FileOutputStream(filename);
os.write(image.getImageAsBytes());
os.flush();
os.close();
PdfDictionary imageDictionary = image.getDictionary();
PRStream maskStream = (PRStream) imageDictionary.getAsStream(PdfName.SMASK);
if (maskStream != null)
{
PdfImageObject maskImage = new PdfImageObject(maskStream);
filename = String.format("%s-%s-mask.%s", name, number, maskImage.getFileType());
os = new FileOutputStream(filename);
os.write(maskImage.getImageAsBytes());
os.flush();
os.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
As you see the ImageRenderListener method renderImage retrieves an argument ImageRenderInfo. This arguments has methods
getStartPoint giving you a vector in User space representing the start point of the xobject and
getImageCTM giving you the coordinate transformation matrix active when this image was rendered. Coordinates are in User space.
The latter gives you the information which exact manipulation on a 1x1 user space unit square are used to actually draw the image. As you are aware, an image may be rotated, stretched, skewed, and moved (the former method actually extracts its result from the matrix from the "moved" information).

Position of JLabel in Graphics when double buffering

I am using a thread to draw some animations, so I need to repaint the label for every frame. To do this without flickering I am updating the label with my backbuffer graphics object (using the lbl.update(bufferedGraphics); method), but when I do this, the label gets repainted in the top left of the Graphics object, and not where setLocation has specified.
How do I specify the location of the label within the graphics, instead of within the panel that owns the label?
Here is an SSCCE:
import javax.swing.*;
import java.awt.*;
public class LabelSSCCE extends JApplet implements Runnable {
JPanel pnl;
JLabel lbl;
Image buffer;
Graphics bufferedGraphics;
Thread t;
public void init (){
pnl = new JPanel (null);
lbl = new JLabel ();
lbl.setText ("Text");
lbl.setOpaque(true);
add(pnl);
pnl.add (lbl);
lbl.setLocation(100, 100);
lbl.setBounds (100, 100, 200, 20);
buffer = createImage (500, 500);
bufferedGraphics = buffer.getGraphics ();
t = new Thread (this, "Label");
t.start ();
}// init method
public void paint (Graphics g){
if (g != null)
g.drawImage (buffer, 0, 0, this);
}//paint
public void update (Graphics g){
paint (g);
}//update
public void render (){
bufferedGraphics.setColor (Color.WHITE);
bufferedGraphics.fillRect (0, 0, 500, 500);
lbl.update (bufferedGraphics);
update(getGraphics());
}//render
public void run (){
while (true){
try{
render ();
t.sleep (20);
} catch (InterruptedException e){
e.printStackTrace ();
}//catch
}//while
}//run
}//LabelSSCCE
First, convert the JLabel to a BufferedImage:
public BufferedImage componentToImage(Component component)
{
BufferedImage img = new BufferedImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
Graphics g = img.getGraphics();
g.setColor(component.getForeground());
g.setFont(component.getFont());
component.paintAll(g);
Rectangle region = new Rectangle(0, 0, img.getWidth(), img.getHeight());
return img.getSubimage(region.x, region.y, region.width, region.height);
}
Then, change the render method to something like this:
public void render() {
bufferedGraphics.setColor(Color.WHITE);
bufferedGraphics.fillRect(0, 0, 500, 500);
BufferedImage bi = componentToImage(lbl);
bufferedGraphics.drawImage(bi, lbl.getX(), lbl.getY(), null);
update(getGraphics());
}

Copying the image of a ScatterChart to system clipboard in JavaFX 2.0

I need to copy a ScatterChart in JavaFX 2.0 to the system clipboard. I'm not really sure how to copy the whole image of the ScatterChart with the potted points.
Gets rid of the need for any bots to take screenshots
/**
* Sets the image content of the clipboard to the chart supplied
* #param chart chart you wish to copy to the clipboard
*/
public void copyChartToClipboard(ScatterChart<Double, Double> chart) {
WritableImage image = chart.snapshot(new SnapshotParameters(), null);
ClipboardContent cc = new ClipboardContent();
cc.putImage(image);
Clipboard.getSystemClipboard().setContent(cc);
}
See next piece of code. I've added full package names for all non-javafx classes to avoid imports mess.
public void start(final Stage primaryStage) throws Exception {
VBox root = new VBox();
final Scene scene;
primaryStage.setScene(scene = new Scene(root));
NumberAxis xAxis = new NumberAxis("X-Axis", 0d, 8.0d, 1.0d);
NumberAxis yAxis = new NumberAxis("Y-Axis", 0.0d, 5.0d, 1.0d);
ObservableList<XYChart.Series> data = FXCollections.observableArrayList(
new ScatterChart.Series("Series 1", FXCollections.<ScatterChart.Data>observableArrayList(
new XYChart.Data(0.2, 3.5),
new XYChart.Data(0.7, 4.6),
new XYChart.Data(7.8, 4.0))));
final ScatterChart chart = new ScatterChart(xAxis, yAxis, data);
Button btnShoot = new Button("screenshot");
btnShoot.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
try {
// getting screen coordinates
Bounds b = chart.getBoundsInParent();
int x = (int)Math.round(primaryStage.getX() + scene.getX() + b.getMinX());
int y = (int)Math.round(primaryStage.getY() + scene.getY() + b.getMinY());
int w = (int)Math.round(b.getWidth());
int h = (int)Math.round(b.getHeight());
// using ATW robot to get image
java.awt.Robot robot = new java.awt.Robot();
java.awt.image.BufferedImage bi = robot.createScreenCapture(new java.awt.Rectangle(x, y, w, h));
// convert BufferedImage to javafx.scene.image.Image
java.io.ByteArrayOutputStream stream = new java.io.ByteArrayOutputStream();
ImageIO.write(bi, "png", stream);
Image image = new Image(new java.io.ByteArrayInputStream(stream.toByteArray()), w, h, true, true);
// put it to clipboard
ClipboardContent cc = new ClipboardContent();
cc.putImage(image);
Clipboard.getSystemClipboard().setContent(cc);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
root.getChildren().addAll(chart, btnShoot);
primaryStage.show();
}
N.B.: this approach involves using AWT side-by-side with JavaFX which is generally not a good idea and may not work on all configuration. It's better to use GlassRobot instead of AWTRobot. Unfortunately it's not stable enough yet.

Duplicate Windows 7 Image Folder 3d Thumbnail

I want to programmatically create a thumbnail from a folder of images, that would look similar to the Windows 7 images folder style like the pic I uploaded here. I have a routine that will add images on top of each other, and rotating them in the x-axis, but I think I need some Y rotation or something to make this illusion complete. I have actually done this with the Windows7APICodePack with the thumbnail methods there, but it seems to force you to have Explorer in the Large Icons mode. I do not want this to depend on Explorer. Nor do I want to use WPF (ViewPort3d). Here is what I want it to look like:
FinalImage http://www.chuckcondron.com/folderexample.JPG
Here is what I have done so far:
StitchedImageThumb http://www.chuckcondron.com/stitchedImageThumb.jpg
As you can see my attempt is not that pretty, nor do the pics come out of the cream color folder (really could use the actual folder pic as well, but not sure how to do that).
current code (c#)
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
namespace ThumbnailCreator
{
public partial class Form1: Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//get all the files in a directory
string[] files = Directory.GetFiles(#"C:\MyImages");
//combine them into one image
Bitmap stitchedImage = Combine(files);
if(File.Exists("stitchedImage.jpg")) File.Delete("stitchedImage.jpg");
//save the new image
stitchedImage.Save(#"stitchedImage.jpg", ImageFormat.Jpeg);
if (File.Exists("stitchedImage.jpg"))
{
FileStream s = File.Open("stitchedImage.jpg", FileMode.Open);
Image temp = Image.FromStream(s);
s.Close();
pictureBox1.Image = temp;
}
CreateThumb(#"stitchedImage.jpg", #"stitchedImageThumb.jpg");
}
public Bitmap Combine(string[] files)
{
//read all images into memory
List<Bitmap> images = new List<Bitmap>();
Bitmap finalImage = null;
try
{
int width = 0;
int height = 0;
int rotate = 7;
foreach (string image in files)
{
//create a Bitmap from the file and add it to the list
Bitmap bitmap = new Bitmap(image);
bitmap = RotateImage(bitmap, rotate);
//update the size of the final bitmap
//width += bitmap.Width;
width = 2500;
//height = bitmap.Height > height ? bitmap.Height : height;
height = 1000;
images.Add(bitmap);
rotate += 5;
}
//create a bitmap to hold the combined image
finalImage = new Bitmap(width, height);
//get a graphics object from the image so we can draw on it
using (Graphics g = Graphics.FromImage(finalImage))
{
//set background color
g.Clear(Color.Goldenrod);
//go through each image and draw it on the final image
ImageAttributes ia = new ImageAttributes();
ColorMatrix cm = new ColorMatrix();
cm.Matrix33 = 0.75f;
ia.SetColorMatrix(cm);
foreach (Bitmap image in images)
{
Image rotatedImage = new Bitmap(image);
g.DrawImage(rotatedImage, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, ia);
}
}
return finalImage;
}
catch (Exception ex)
{
if (finalImage != null)
finalImage.Dispose();
throw ex;
}
finally
{
//clean up memory
foreach (System.Drawing.Bitmap image in images)
{
image.Dispose();
}
}
}
public void CreateThumb(string source, string destination)
{
Image imgThumb = null;
try
{
Image image = null;
// Check if image exists
image = Image.FromFile(source);
if (image != null)
{
imgThumb = image.GetThumbnailImage(100, 100, null, new IntPtr());
imgThumb.Save(destination);
image.Dispose();
}
}
catch
{
MessageBox.Show("An error occured");
}
if (File.Exists(destination))
{
FileStream s = File.Open(destination, FileMode.Open);
Image temp = Image.FromStream(s);
s.Close();
pictureBox2.Image = temp;
}
}
private Bitmap RotateImage(Bitmap inputImg, double degreeAngle)
{
//Corners of the image
PointF[] rotationPoints = { new PointF(0, 0),
new PointF(inputImg.Width, 0),
new PointF(0, inputImg.Height),
new PointF(inputImg.Width, inputImg.Height)};
//Rotate the corners
PointMath.RotatePoints(rotationPoints, new PointF(inputImg.Width / 2.0f, inputImg.Height / 2.0f), degreeAngle);
//Get the new bounds given from the rotation of the corners
//(avoid clipping of the image)
Rectangle bounds = PointMath.GetBounds(rotationPoints);
//An empy bitmap to draw the rotated image
Bitmap rotatedBitmap = new Bitmap(bounds.Width *2, bounds.Height *2);
using (Graphics g = Graphics.FromImage(rotatedBitmap))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//Transformation matrix
Matrix m = new Matrix();
m.RotateAt((float)degreeAngle, new PointF(inputImg.Width / 2.0f, inputImg.Height / 2.0f));
m.Translate(-bounds.Left, -bounds.Top, MatrixOrder.Append); //shift to compensate for the rotation
g.Transform = m;
g.DrawImage(inputImg, 0, 0);
}
return rotatedBitmap;
}
}
}

Resources