I am trying to display a random image URL retrieved via the UnSplash API on a processing screen. There are two issues I think: 1) the url delivered does not have a supported extension such as .jpg etc. It looks like this for example:
https://images.unsplash.com/photo-1672710509828-c971003d3533?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=Mnw0MDM3NDd8MHwxfHJhbmRvbXx8fHx8fHx8fDE2NzQ5MzI4OTM&ixlib=rb-4.0.3&q=80&w=400
I also imagine that an issue might be that the image is not local?
Can anyone help me with this?
Tracy
PImage IMG;
void setup () {
size(1000, 1000);
background (255);
IMG = loadImage("https://images.unsplash.com/photo-1672710509828-c971003d3533?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=Mnw0MDM3NDd8MHwxfHJhbmRvbXx8fHx8fHx8fDE2NzQ5MzI4OTM&ixlib=rb-4.0.3&q=80&w=400");
}
void draw() {
image(IMG, 0, 0);
}
I get an error saying cannot load because it does not have a typical image extension.
Thanks for the help.
One workaround is to add your own URL encoded variable with the sole purpose of ending the URL with ".jpg"
Here's a basic example:
PImage img;
void setup(){
size(400, 600);
noLoop();
String originalURL = "https://images.unsplash.com/photo-1672710509828-c971003d3533?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=Mnw0MDM3NDd8MHwxfHJhbmRvbXx8fHx8fHx8fDE2NzQ5MzI4OTM&ixlib=rb-4.0.3&q=80&w=400";
img = loadImage(originalURL + "&p5=image.jpg");
}
void draw(){
image(img, 0, 0);
}
Related
I have load an image in QGraphicsView, but consider of the size of QGraphicsView scene, I need to scale the image first, then add the scaled image to scene.
e.g. The image original size is 1536*1024, the QGraphicsView size is 500*400, firstly I scale the image like this:
image2D = image2D.scaled( h * P , h, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
myScene->setSceneRect((h * P-w)/2, 0, h * P , h);
pixmapItem = new QGraphicsPixmapItem(image2D);
myScene->addItem(pixmapItem);
myView->setScene(myScene);
And now a problem comes to me, when wheelEvent happends and the QGraphicsView zoom in, the scaled image becomes indistinct while I want it to keep as clear as the original one.
I find a way that I can hold an original copy of image, then when wheelEvent happend just scale the original copy and put it to scene.
But I don't know how to write this code, thanks for help~
or are there any simple methods?
class interactiveView : public QGraphicsView
{
protected:
void wheelEvent(QWheelEvent *event) override;
}
void interactiveView::wheelEvent(QWheelEvent *event)
{
int scrollAmount = event->delta();
xPos = event->pos().x();
yPos = event->pos().y();
scrollAmount > 0 ? zoomIn() : zoomOut();
}
Update:
I find a simple way like this:
just use QGraphicsView::fitInView() to make sure that the image scale is equal to QGraphicsView, and do not need to scale image first.
Therefore the image won't be indistinct when zoom in, and I only need to recall the QGraphicsView::fitInView() to reset to original view instead of using QGraphicsView::resetMatrix()
void myImageWindow::loadImag(int w, int h)
{
pixmapItem->setPixmap(image2D);
//if the scale of image changed
if(image2D.height() != imgHeight_pre){
myView->fitInView(pixmapItem, Qt::KeepAspectRatioByExpanding);
imgHeight_pre = image2D.height();
}
//if the scene of QGraphicsView changed
if(h != sceneHeight_pre){
myView->fitInView(pixmapItem, Qt::KeepAspectRatioByExpanding);
sceneHeight_pre = h;
}
}
void myImageWindow::on_rstImgBtn_clicked()
{
myView->fitInView(pixmapItem, Qt::KeepAspectRatioByExpanding);
}
Scaled image:
becomes indistinct when zoom in:
You can use this method resetMatrix() to reset image
For example:
graphicsView->scale(2, 2);
graphicsView->resetMatrix();
graphicsView->scale(1, 1);
I'm developing a GUI for Arduino mega 2560 using Processing (control p5 library).
My board senses analog pin A0 and continuously displays its value as string in console. If a specific digital pin goes high then It sends the error string to processing console and waits for reset to be pressed.
Ex: A1-B1 error press reset
If A1-B1 is error then I want my GUI to fill the rectangle with red along with displaying string
" A1-B1 error press reset"
How to I do this?
Here's my processing code
import java.util.*;
import at.mukprojects.console.*;
Console console;
import processing.serial.*;
Serial port;
import controlP5.*;
ControlP5 cp5;
int myColorBackground = color(0, 0, 0);
float k,l;
String val;
int i;
char a;
void setup() {
size(800,600);
frame.setResizable(true);
smooth();
noStroke();
printArray(Serial.list());
port = new Serial(this,Serial.list()[0],9600);
port.bufferUntil(10);
cp5 = new ControlP5(this); //init gui lib
console = new Console(this); //init console
console.start();
}
void draw() {
background(myColorBackground);
fill(250, 131, 3); //text color
console.draw();
k= (width*0.75);
l=(0.25*height)-50;
fill(0);
stroke(250, 131, 1);
rect(k+20, l+20, 12,12);
fill(250, 131, 3);
textFont(font, 16);
text("A1-B1", k+100, l+20);
}
void serialEvent(Serial myPort) {
while(port.available()>0){
val = port.readStringUntil(10);
}
if (val!=null)
{
println(val);
}
}
The best advice we can give you is to break your problem down into smaller steps and take those pieces on one at a time.
For example, can you create a simple sketch that displays a message after the mouse has been clicked? Forget about the Arduino for a minute and just get this working by itself. It might look something like this:
boolean mouseWasPressed = false;
void draw(){
if(mouseWasPressed){
background(255, 0 , 0);
}
}
void mousePressed(){
mouseWasPressed = true;
}
Separately from that, get a sketch working that just shows the Arduino message in the console. It sounds like you might already have a lot of that done, but try to isolate it in a small example program.
When you have both of those working separately, then you can start thinking about combining them into one program. And if you get stuck, you can post a MCVE showing exactly which step you're stuck on. Good luck.
I'm trying to load the image in a separate class and draw it in the main draw function. I get such an error:
The method image(PImage, float, float) in the type PApplet is not applicable for the arguments (main.image, int, int)
Here is the Image class code:
class Image{
PImage img;
Image(){
img = new PImage();
img = loadImage("test.jpg"); }
}
And here is the main file:
Image img;
void setup(){
img = new Image(this);
}
void draw(){
image(img, 0, 0);
}
Can anyone help please?
The error says it all: Processing doesn't know how to draw your Image class. It doesn't magically know to use the PImage img from your Image class. You have to specifically tell it to use the PImage:
void draw(){
image(img.img, 0, 0);
}
Your naming scheme makes that look a little awkward, but you're referring to the PImage image of your Image named img and telling Processing to draw that instead.
You might want to use a getPImage() function instead of referring to the variable directly. Also note that you're passing the PApplet into the Image constructor using the this keyword, but your Image constructor does not take any arguments.
How to create more than one window of a single sketch in Processing?
Actually I want to detect and track a particular color (through webcam) in one window and display the detected co-ordinates as a point in another window.Till now I'm able to display the points in the same window where detecting it.But I want to split it into two different windows.
You need to create a new frame and a new PApplet... here's a sample sketch:
import javax.swing.*;
SecondApplet s;
void setup() {
size(640, 480);
PFrame f = new PFrame(width, height);
frame.setTitle("first window");
f.setTitle("second window");
fill(0);
}
void draw() {
background(255);
ellipse(mouseX, mouseY, 10, 10);
s.setGhostCursor(mouseX, mouseY);
}
public class PFrame extends JFrame {
public PFrame(int width, int height) {
setBounds(100, 100, width, height);
s = new SecondApplet();
add(s);
s.init();
show();
}
}
public class SecondApplet extends PApplet {
int ghostX, ghostY;
public void setup() {
background(0);
noStroke();
}
public void draw() {
background(50);
fill(255);
ellipse(mouseX, mouseY, 10, 10);
fill(0);
ellipse(ghostX, ghostY, 10, 10);
}
public void setGhostCursor(int ghostX, int ghostY) {
this.ghostX = ghostX;
this.ghostY = ghostY;
}
}
One option might be to create a sketch twice the size of your original window and just offset the detected coordinates by half the sketch's size.
Here's a very rough code snippet (assumming blob will be a detected color blob):
int camWidth = 320;
int camHeight = 240;
Capture cam;
void setup(){
size(camWidth * 2,camHeight);
//init cam/opencv/etc.
}
void draw(){
//update cam and get data
image(cam,0,0);
//draw
rect(camWidth+blob.x,blob.y,blob.width,blob.height);
}
To be honest, it might be easier to overlay the tracked information. For example, if you're doing color tracking, just display the outlines of the bounding box of the tracked area.
If you really really want to display another window, you can use a JPanel.
Have a look at this answer for a running code example.
I would recommend using G4P, a GUI library for Processing that has some functionality built in for handling multiple windows. I have used this before with a webcam and it worked well. It comes with a GWindow object that will spawn a window easily. There is a short tutorial on the website that explains the basics.
I've included some old code that I have that will show you the basic idea. What is happening in the code is that I make two GWindows and send them each a PImage to display: one gets a webcam image and the other an effected image. The way you do this is to augment the GWinData object to also include the data you would like to pass to the windows. Instead of making one specific object for each window I just made one object with the two PImages in it. Each GWindow gets its own draw loop (at the bottom of the example) where it loads the PImage from the overridden GWinData object and displays it. In the main draw loop I read the webcam and then process it to create the two images and then store them into the GWinData object.
Hopefully that gives you enough to get started.
import guicomponents.*;
import processing.video.*;
private GWindow window;
private GWindow window2;
Capture video;
PImage sorted;
PImage imgdif; // image with pixel thresholding
MyWinData data;
void setup(){
size(640, 480,P2D); // Change size to 320 x 240 if too slow at 640 x 480
// Uses the default video input, see the reference if this causes an error
video = new Capture(this, 640, 480, 24);
numPixels = video.width * video.height;
data = new MyWinData();
window = new GWindow(this, "TEST", 0,0, 640,480, true, P2D);
window.isAlwaysOnTop();
window.addData(data);
window.addDrawHandler(this, "Window1draw");
window2 = new GWindow(this, "TEST", 640,0 , 640,480, true, P2D);
window2.isAlwaysOnTop();
window2.addData(data);
window2.addDrawHandler(this, "Window2draw");
loadColors("64rev.csv");
colorlength = mycolors.length;
distances = new float[colorlength];
noCursor();
}
void draw()
{
if (video.available())
{
background(0);
video.read();
image(video,0,0);
loadPixels();
imgdif = get(); // clones the last image drawn to the screen v1.1
sorted = get();
/// Removed a lot of code here that did the processing
// hand data to our data class to pass to other windows
data.sortedimage = sorted;
data.difimage = imgdif;
}
}
class MyWinData extends GWinData {
public PImage sortedimage;
public PImage difimage;
MyWinData(){
sortedimage = createImage(640,480,RGB);
difimage = createImage(640,480,RGB);
}
}
public void Window1draw(GWinApplet a, GWinData d){
MyWinData data = (MyWinData) d;
a.image(data.sortedimage, 0,0);
}
public void Window2draw(GWinApplet a, GWinData d){
MyWinData data = (MyWinData) d;
a.image(data.difimage,0,0);
}
I'm new to working with PdfBox and I'm having a small issue when displaying images. I'm able to import the image, which is sized at 800*900 pixels, and looks fine when viewed in an existing pdf at 100%. However when the resulting PDF is generated using the below code, the image becomes blurry, and the image extends beyond the boundaries of the A4 page.
Is there a different way of sizing/saving images so that they display correctly in pdfbox?
public class PDFtest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException, COSVisitorException {
// TODO code application logic here
// Create a document and add a page to it
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
// Create a new font object selecting one of the PDF base fonts
PDFont font = PDType1Font.HELVETICA_BOLD;
InputStream in = new FileInputStream(new File("img.jpg"));
PDJpeg img = new PDJpeg(document, in);
// Start a new content stream which will "hold" the to be created content
PDPageContentStream contentStream = new PDPageContentStream(document, page);
// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
contentStream.drawImage(img, 10, 700);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.moveTextPositionByAmount(10, 650);
contentStream.drawString("Hello World");
contentStream.endText();
// Make sure that the content stream is closed:
contentStream.close();
// Save the results and ensure that the document is properly closed:
document.save("Hello World.pdf");
document.close();
}
I'd like to point out that as of 2.0 the contentStream.drawXObject function call in Victor's answer is deprecated. If you want to specify a width and height you should use contentStream.drawImage(image, x, y, width, height)
I had the same problem asked in this question, but the given answer is not right.
After some research I found a solution.
Instead of using the function drawImage use the function drawXObject
contentStream.drawXObject( img, 10, 700, 100, 100 );
Where the last two numbers specify the size of the image to be drawn.
For similar situation, for me, with PDF 2.0.11 and a tiff file of dimensions - 1600 x 2100 the following code perfectly fit the image in A4 (portrait) size. Not sure if PDFRectangle is okay with you.
I got this example straight from PDFBOX - Example
The only thing I tweaked/introduced is:
PDRectangle.A4.getWidth(), PDRectangle.A4.getHeight()
Here is the full sample:
public static void main(String[] args) throws IOException
{
// if (args.length != 2)
// {
// System.err.println("usage: " + ImageToPDF.class.getName() + " <image> <output-file>");
// System.exit(1);
// }
String imagePath = "C:/FAX/sample.tiff";
String pdfPath = "C:/FAX/sample.pdf";
if (!pdfPath.endsWith(".pdf"))
{
System.err.println("Last argument must be the destination .pdf file");
System.exit(1);
}
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
// createFromFile is the easiest way with an image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
// draw the image at full size at (x=20, y=20)
try (PDPageContentStream contents = new PDPageContentStream(doc, page))
{
// draw the image at full size at (x=20, y=20)
contents.drawImage(pdImage, 0, 0, PDRectangle.A4.getWidth(), PDRectangle.A4.getHeight());
// to draw the image at half size at (x=20, y=20) use
// contents.drawImage(pdImage, 20, 20, pdImage.getWidth() / 2, pdImage.getHeight() / 2);
}
doc.save(pdfPath);
System.out.println("Tiff converted to PDF succussfully..!");
}
}
Hope it helps.
If your intention is an A4 sized pic on a PDF, then i guess you find the actual size of typical A4 in pixels.
Also you should be aware of the extension of the picture that you want to view like jpg, gif, or bmp ...
from what I saw in your code, the dimensions of the picture are 10 X 700 which I believe is pretty small size.
contentStream.drawImage(img, 10, 700);
And the extension of the picture is : jpg
InputStream in = new FileInputStream(new File("img.jpg"));
check those and return for more info.
that's all.
good luck'''
As per the new API 2.0.x, one can use the PDRectangle to fetch Pdf page width and height. One can use PDPageContentStream to draw the image in accordance with PDF page.
For reference:
try (PDPageContentStream contents = new PDPageContentStream(pdDocument, pdPage)) {
final PDRectangle mediaBox = pdPage.getMediaBox();
final PDImageXObject pdImage = PDImageXObject.createFromFile(image, pdDocument);
contents.drawImage(pdImage, 0, 0, mediaBox.getWidth(), mediaBox.getHeight());
}