How can put image back of paints which i drew? - processing

The thing what I want to make is similar to paint program.
The problem is when I draw some lines(Not just lines. Whole things I drew are included in this case.), those lines only drawn back of a image I put in before I draw that.
At first, I thought it was just problem of code's order. But it wasn't.
I just want draw some lines on the image like paint program.
Like this:enter image description here

You can paint into a separate "layer" using PGraphics.
Once you initialise an instance you can use the typical drawing methods within beginDraw() / endDraw() (as the reference example suggests).
The only thing left is to save the final image which is simple enough using save()
Here's a modified example of Examples > Basics > Image > LoadDisplay which uses a separate PGraphics instance to draw into as the mouse is dragged and saves the final image when the s key is pressed:
/**
* Based on Examples > Basics > Image > Load and Display
*
* Images can be loaded and displayed to the screen at their actual size
* or any other size.
*/
PImage img; // Declare variable "a" of type PImage
// reference to layer to draw into
PGraphics paintLayer;
void setup() {
size(640, 360);
// The image file must be in the data folder of the current sketch
// to load successfully
img = loadImage("moonwalk.jpg"); // Load the image into the program
// create a separate layer to draw into
paintLayer = createGraphics(width,height);
}
void draw() {
// Displays the image at its actual size at point (0,0)
image(img, 0, 0);
// Displays the paint layer
image(paintLayer,0,0);
}
void mouseDragged(){
// use drawing commands between beginDraw() / endDraw() calls
paintLayer.beginDraw();
paintLayer.line(mouseX,mouseY,pmouseX,pmouseY);
paintLayer.endDraw();
}
void keyPressed(){
if(key == 's'){
saveFrame("annotated-image.png");
}
}

Related

Why X/Y coordinators of image in pdf are always ZERO by GetImageCTM?

I am searching for a long time on net. But no use.
Please help or try to give some ideas how to achieve this.
Any help will be appreciated.
I get the Matrix by ImageRenderInfo#GetImageCTM(), and get the X/Y coordiantors.
but it is always 0!
I have tried these api, GetStartPoint(), and GetImageCTM.
However, the X/Y coordinator is always 0 :-(
Note: I have some images in pdf in some positons(not the (0,0) coordinator).
void IRenderListener.RenderImage(ImageRenderInfo imgRenderInfo)
{
Matrix mtx = imgRenderInfo.GetImageCTM();
// x, y
float[] coordinate = new float[] { mtx[Matrix.I31], mtx[Matrix.I32] };
// Why the coordinate[0] and coordinate[1]
// are always be ZERO regardless the positon in Pdf
}
Answer to the question as is
I parsed the page contents of an arbitrary file I had at hands (the example PDF from this question) using a render listener with your implementation code plus output of the coordinates:
public void ExtractImageCoordinatesFromArchmodels()
{
using (PdfReader reader = new PdfReader(#"EVERMOTION ARCHMODELS VOL.78.pdf"))
{
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
ImageCoordinatesRenderListener listener = new ImageCoordinatesRenderListener();
for (var i = 1; i <= reader.NumberOfPages; i++)
{
parser.ProcessContent(i, listener);
}
}
}
internal class ImageCoordinatesRenderListener : IRenderListener
{
public void BeginTextBlock()
{ }
public void EndTextBlock()
{ }
public void RenderText(TextRenderInfo renderInfo)
{ }
public void RenderImage(ImageRenderInfo renderInfo)
{
Matrix mtx = renderInfo.GetImageCTM();
// x, y
float[] coordinate = new float[] { mtx[Matrix.I31], mtx[Matrix.I32] };
Console.WriteLine("Image at {0}, {1}.", coordinate[0], coordinate[1]);
}
}
and the output was
Image at 6,00029, 52,15466.
Image at 19,84251, 363,4501.
Image at 294,091, 361,5604.
Image at 300,0336, 81,089.
Image at 15,59055, 72,94052.
Image at 5,322647, 340,7029.
Image at 288,5311, 386,0621.
Image at 291,7613, 69,35573.
Image at 28,50845, 53,13286.
Image at 41,2021, 380,3172.
Image at 290,8796, 368,9564.
Image at 295,8532, 50,71478.
Image at 19,13385, 49,21146.
Image at 25,5118, 385,9343.
Image at 282,4584, 379,8427.
Image at 293,5927, 65,19702.
Image at 4,535416, 60,35075.
Image at 3,364258, 374,4344.
Image at 288,0557, 373,5591.
Image at 299,9102, 59,13971.
Image at 11,33858, 66,10181.
Image at 11,66959, 380,3134.
Image at 297,1836, 378,4615.
Image at 299,9689, 66,74164.
Image at 10,62991, 53,18137.
Image at 5,180252, 377,7065.
Image at 279,9567, 377,9544.
Image at 289,9219, 69,23323.
Image at 6,400314, 68,17795.
Image at 11,33858, 361,2458.
Image at 297,1935, 373,4553.
Image at 299,8854, 68,30142.
Image at 7,086609, 68,13367.
Image at 3,82518, 352,3451.
Image at 287,9208, 373,4846.
Image at 294,6425, 68,3132.
Image at 41,2271, 68,15968.
Image at 5,709488, 356,2161.
Image at 304,9857, 373,593.
Image at 282,4557, 48,97745.
Image at 5,669281, 53,65367.
Image at 27,34265, 382,0123.
Image at 297,1409, 373,494.
Image at 300,0584, 50,23624.
Image at 7,245102, 68,23528.
Image at 8,503922, 380,1963.
Image at 290,1901, 355,9355.
Image at 287,2598, 60,53516.
Image at 5,102356, 68,01541.
Image at 17,00786, 378,9057.
Image at 296,8928, 373,5667.
Image at 299,9655, 68,04535.
(My locale uses a comma as decimal separator.)
So I cannot reproduce your claim
the X/Y coordinator is always 0
Thus, what you observed is either due to some issue of your remaining code or something special about all your test PDFs; probably they simply indeed all have their images positioned at 0,0
Clarifications from comments
Meanwhile the OP has clarified in comments that the images of interest are located in annotation appearance streams, not in the page content stream.
Coordinates therein are in the respective annotation appearance stream coordinate system which is implied by the appearance's bounding box (its BBox entry). This bounding box then optionally is transformed by the appearance matrix (its Matrix entry). The resulting four sided area then is scaled and moved into the annotation's rectangle (its Rect entry). And depending on page rotation and annotation properties, this rectangle may be rotated by a multiple of 90° relative to the page coordinates.
Thus, a general solution transforming those coordinates into the default user space coordinate system of the page requires some math.
Often, though, bitmaps in annotation appearances are filling the bounding box (nearly) completely. Often there is no appearance matrix. And often annotations rotate with the page.
Thus, an often good approximation is to simply use the annotation rectangle. This also is what the OP now uses.

How to overlay an image over another in P3D

In processing.js, how would you overlay an image over another one in P3D mode?
Here is my code:
/* #pjs preload="duck.jpg"; */
/* #pjs preload="a.png"; */
PImage imageDuck;
PImage imageA;
void setup() {
size(500, 500, P3D);
imageDuck = loadImage("duck.jpg");
imageA = loadImage("a.png");
}
void draw() {
background(255);
noStroke();
image(imageDuck, 0, 0);
image(imageA, 0, 0);
}
So what the code trying to do is to display a duck image, then overlay another image name a.png (with transparent background) on top of it.
When I use the normal size(500, 500); without the P3D mode, the image overlay works perfectly.
However, I am using P3D because the next thing I am going to do is to rotate my images together.
So in this size(500, 500, P3D) mode, I can see my a.png flashed once, then only my duck image shows. If I comment out duck, a.png will show. If I comment out a.png, my duck shows. If I reorder the image() call, still only the duck image shows. I added translate(0,0,-1) or translate(0,0,1) in between my image() calls, no luck, only my duck image shows.
Is this even possible?
I resolved my problem, it is the first line #pjs, can only be called once. Multiple images will have to be preloaded within one single line. In my example, my first 2 lines will have to be combined like such:
/* #pjs preload="duck.jpg,a.png"; */

How can I clear the canvas using one click in processing?

I was trying to make a very simple game but I'm having trouble with mouse events. I want to only click once and the whole canvas will be cleared but what happen is it keeps on coming back to its original canvas if I'm not clicking anymore.
if((mouseX >= 100) && (mouseX <= 235) &&
(mouseY >= 490) && (mouseY <= 540) &&
(mousePressed))
{
clear ();
slide1 ();
}
This is the second tab:
void slide1()
{
clear ();
background (30);`enter code here`
slide1 = loadImage ("slide1.jpg");
image (slide1,100,0,400,300);
}
Without seeing a complete, working example, it is difficult to tell for certain. However, it seems likely that you have confused clear() and background(). The easiest way to wipe the screen is by calling background() -- for example at the beginning of every draw() frame.
From the Processing reference:
clear(): "Clears the pixels within a buffer. This function only works on PGraphics objects"
background(): "This function is typically used within draw() to clear the display window at the beginning of each frame, but it can be used inside setup() to set the background on the first frame of animation or if the backgound need only be set once."
e.g. (based on your code):
PImage slide1;
void setup(){
size(512,512);
slide1 = loadImage ("https://processing.org/img/processing3-logo.png");
}
void draw(){
background (30); // clear screen every frame
if(mousePressed) { // show image whenever mouse is down
image (slide1,0,0);
}
}
This always clears the canvas.
Alternately, if you only want to wipe the canvas on a click, don't call background each draw -- instead, call background only on mousePressed. However, in your case (showing an image) it looks like you might also want to wipe again on mouseReleased (so that the image disappears). You may wish to use the built-in mousePressed() and mouseReleased() Processing functions for this and call background in each one.
I don't think this is what you actually want, but: the actual answer to the title question ("How can I clear the canvas using one click in processing?") is:
void draw(){
line(mouseX,mouseY,pmouseX,pmouseY);
}
void mouseClicked(){
background(192);
}

Is it possible to save a generated image in Codename One?

My question is related to this previous question. What I want to achieve is to stack images (they have transparency), write a string on top, and save the photomontage / photocollage with full resolution.
#Override
protected void beforeMain(Form f) {
Image photoBase = fetchResourceFile().getImage("Voiture_4_3.jpg");
Image watermark = fetchResourceFile().getImage("Watermark.png");
f.setLayout(new LayeredLayout());
final Label drawing = new Label();
f.addComponent(drawing);
// Image mutable dans laquelle on va dessiner (fond blanc)
Image mutableImage = Image.createImage(photoBase.getWidth(), photoBase.getHeight());
drawing.getUnselectedStyle().setBgImage(mutableImage);
drawing.getUnselectedStyle().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FIT);
// Paint all the stuff
paints(mutableImage.getGraphics(), photoBase, watermark, photoBase.getWidth(), photoBase.getHeight());
// Save the collage
Image screenshot = Image.createImage(photoBase.getWidth(), photoBase.getHeight());
f.revalidate();
f.setVisible(true);
drawing.paintComponent(screenshot.getGraphics(), true);
String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
err.printStackTrace();
}
}
public void paints(Graphics g, Image background, Image watermark, int width, int height) {
g.drawImage(background, 0, 0);
g.drawImage(watermark, 0, 0);
g.setColor(0xFF0000);
// Upper left corner
g.fillRect(0, 0, 10, 10);
// Lower right corner
g.setColor(0x00FF00);
g.fillRect(width - 10, height - 10, 10, 10);
g.setColor(0xFF0000);
Font f = Font.createTrueTypeFont("Geometos", "Geometos.ttf").derive(220, Font.STYLE_BOLD);
g.setFont(f);
// Draw a string right below the M from Mercedes on the car windscreen (measured in Gimp)
g.drawString("HelloWorld",
(int) (848 ),
(int) (610)
);
}
This is the saved screenshot I get if I use the Iphone6 skin (the payload image is smaller than the original one and is centered). If I use the Xoom skin this is what I get (the payload image is still smaller than the original image but it has moved to the left).
So to sum it all up : why is the saved screenshot with Xoom skin different from the one I get with Iphone skin ? Is there anyway to directly save the graphics on which I paint in the paints method so that the saved image would have the original dimensions ?
Thanks a lot to anyone that could help me :-)!
Cheers,
You can save an image in Codename one using the ImageIO class. Notice that you can draw a container hierarchy into a mutable image using the paintComponent(Graphics) method.
You can do both approaches with draw image on mutable or via layouts. Personally I always prefer layouts as I like the abstraction but I wouldn't say the mutable image approach is right/wrong.
Notice that if you change/repaint a lot then mutable images are slower (this will not be noticeable for regular code or on the simulator) as they are forced to use the software renderer and can't use the GPU fully.
In the previous question it seems you placed the image with a "FIT" style which naturally drew it smaller than the containing container and then drew the image on top of it manually... This is problematic.
One solution is to draw everything manually but then you will need to do the "fit" aspect of drawing yourself. If you use layouts you should position everything based on the layouts including your drawing/text.

In Processing, how can I save part of the window as an image?

I am using Processing under Fedora 20, and I want to display an image of the extending tracks of objects moving across part of the screen, with each object displayed at its current position at the end of the track. To avoid having to record all the co-ordinates of the tracks, I usesave("image.png"); to save the tracks so far, then draw the objects. In the next frame I use img = loadImage("image.png"); to restore the tracks made so far, without the objects, which would still be in their previous positions.. I extend the tracks to their new positions, then usesave("image.png"); to save the extended tracks, still without the objects, ready for the next loop round. Then I draw the objects in their new positions at the end of their extended tracks. In this way successive loops show the objects advancing, with their previous positions as tracks behind them.
This has worked well in tests where the image is the whole frame, but now I need to put that display in a corner of the whole frame, and leave the rest unchanged. I expect that createImage(...) will be the answer, but I cannot find any details of how to to so.
A similar question asked here has this recommendation: "The PImage class contains a save() function that exports to file. The API should be your first stop for questions like this." Of course I've looked at that API, but I don't think it helps here, unless I have to create the image to save pixel by pixel, in which case I would expect it to slow things down a lot.
So my question is: in Processing can I save and restore just part of the frame as an image, without affecting the rest of the frame?
I have continued to research this. It seems strange to me that I can find oodles of sketch references, tutorials, and examples, that save and load the entire frame, but no easy way of saving and restoring just part of the frame as an image. I could probably do it using Pimage but that appears to require an awful lot of image. in front of everything to be drawn there.
I have got round it with a kludge: I created a mask image (see this Processing reference) the size of the whole frame. The mask is defined as grey areas representing opacity, so that white, zero opacity (0), is transparent and black, fully opaque (255) completely conceals the background image, thus:
{ size (1280,800);
background(0); // whole frame is transparent..
fill(255); // ..and..
rect(680,0,600,600); // ..smaller image area is now opaque
save("[path to sketch]/mask01.jpg");
}
void draw(){}
Then in my main code I use:
PImage img, mimg;
img = loadImage("image4.png"); // The image I want to see ..
// .. including the rest of the frame which would obscure previous work
mimg = loadImage("mask01.jpg"); // create the mask
//apply the mask, allowing previous work to show though
img.mask(mimg);
// display the masked image
image(img, 0, 0);
I will accept this as an answer if no better suggestion is made.
void setup(){
size(640, 480);
background(0);
noStroke();
fill(255);
rect(40, 150, 200, 100);
}
void draw(){
}
void mousePressed(){
PImage img =get(40, 150, 200, 100);
img.save("test.jpg");
}
Old news, but here's an answer: you can use the pixel array and math.
Let's say that this is your viewport:
You can use loadPixels(); to fill the pixels[] array with the current content of the viewport, then fish the pixels you want from this array.
In the given example, here's a way to filter the unwanted pixels:
void exportImage() {
// creating the image to the "desired size"
PImage img = createImage(600, 900, RGB);
loadPixels();
int index = 0;
for(int i=0; i<pixels.length; i++) {
// filtering the unwanted first 200 pixels on every row
// remember that the pixels[] array is 1 dimensional, so some math are unavoidable. For this simple example I use the modulo operator.
if (i % width >= 200) { // "magic numbers" are bad, remember. This is only a simplification.
img.pixels[index] = pixels[i];
index++;
}
}
img.updatePixels();
img.save("test.png");
}
It may be too late to help you, but maybe someone else will need this. Either way, have fun!

Resources