I was interested in uploading images to the imgur API. In the docs to upload the image
import pyimgur
CLIENT_ID = "Your_applications_client_id"
PATH = "A Filepath to an image on your computer"
im = pyimgur.Imgur(CLIENT_ID)
uploaded_image = im.upload_image(PATH, title="Uploaded with PyImgur")
print(uploaded_image.title)
print(uploaded_image.date)
print(uploaded_image.url)
print(uploaded_image.link)
I am curious if someone knows how to instead of using a path( have the image saved locally), just have a link to a image to upload to imgur. I feel like it exists due to the fact with the GUI website you can enter a picture link and can then upload.
Thank you for the help.
The Imgur.upload_image() method takes a url argument, simply pass it a URL of an image to add:
uploaded_image = im.upload_image(url=URL_OF_IMAGE, title="Uploaded with PyImgur")
You must either provide a path or a URL, but not both.
See the upload_image() documentation for all arguments it accepts:
Upload the image at either path or url.
path – The path to the image you want to upload.
url – The url to the image you want to upload.
Related
Context
I have made a simple web app for uploading content to a blog. The front sends AJAX requests (using FormData) to the backend which is Bottle running on Python 3.7. Text content is saved to a MySQL database and images are saved to a folder on the server. Everything works fine.
Image processing and PIL/Pillow
Now, I want to enable processing of uploaded images to standardise them (I need them all resized and/or cropped to 700x400px).
I was hoping to use Pillow for this. My problem is creating a PIL Image object from the file object in Bottle. I cannot initialise a valid Image object.
Code
# AJAX sends request to this route
#post('/update')
def update():
# Form data
title = request.forms.get("title")
body = request.forms.get("body")
image = request.forms.get("image")
author = request.forms.get("author")
# Image upload
file = request.files.get("file")
if file:
extension = file.filename.split(".")[-1]
if extension not in ('png', 'jpg', 'jpeg'):
return {"result" : 0, "message": "File Format Error"}
save_path = "my/save/path"
file.save(save_path)
The problem
This all works as expected, but I cannot create a valid Image object with pillow for processing. I even tried reloading the saved image using the save path but this did not work either.
Other attempts
The code below did not work. It caused an internal server error, though I am having trouble setting up more detailed Python debugging.
path = save_path + "/" + file.filename
image_data = open(path, "rb")
image = Image.open(image_data)
When logged manually, the path is a valid relative URL ("../domain-folder/images") and I have checked that I am definitely importing PIL (Pillow) correctly using PIL.PILLOW_VERSION.
I tried adapting this answer:
image = Image.frombytes('RGBA', (128,128), image_data, 'raw')
However, I won’t know the size until I have created the Image object. I also tried using io:
image = Image.open(io.BytesIO(image_data))
This did not work either. In each case, it is only the line trying to initialise the Image object that causes problems.
Summary
The Bottle documentation says the uploaded file is a file-like object, but I am not having much success in creating an Image object that I can process.
How should I go about this? I do not have a preference about processing before or after saving. I am comfortable with the processing, it is initialising the Image object that is causing the problem.
Edit - Solution
I got this to work by adapting the answer from eatmeimadanish. I had to use a io.BytesIO object to save the file from Bottle, then load it with Pillow from there. After processing, it could be saved in the usual way.
obj = io.BytesIO()
file.save(obj) # This saves the file retrieved by Bottle to the BytesIO object
path = save_path + "/" + file.filename
# Image processing
im = Image.open(obj) # Reopen the object with PIL
im = im.resize((700,400))
im.save(path, optimize=True)
I found this from the Pillow documentation about a different function that may also be of use.
PIL.Image.frombuffer(mode, size, data, decoder_name='raw', *args)
Note that this function decodes pixel data only, not entire images.
If you have an entire image file in a string, wrap it in a BytesIO object, and use open() to load it.
Use StringIO instead.
From PIL import Image
try:
import cStringIO as StringIO
except ImportError:
import StringIO
s = StringIO.StringIO()
#save your in memory file to this instead of a regular file
file = request.files.get("file")
if file:
extension = file.filename.split(".")[-1]
if extension not in ('png', 'jpg', 'jpeg'):
return {"result" : 0, "message": "File Format Error"}
file.save(s)
im = Image.open(s)
im.resize((700,400))
im.save(s, 'png', optimize=True)
s64 = base64.b64encode(s.getvalue())
From what I understand, you're trying to resize the image after it has been saved locally (note that you could try to do the resize before it is saved). If this is what you want to achieve here, you can open the image directly using Pillow, it does the job for you (you do not have to open(path, "rb"):
image = Image.open(path)
image.resize((700,400)).save(path)
url="https://images.data.gov.sg/api/traffic-images/2016/02/96128cfd-ab9a-4959-972e-a5e74bb149a9.jpg"
I am trying this:
import urllib
url="https://images.data.gov.sg/api/traffic-images/2016/02/96128cfd-ab9a-4959-972e-a5e74bb149a9.jpg"
IMAGE=url.rsplit("/")[-1]
urllib.urlretrieve(url,IMAGE)
Image is downloaded in the destination folder after the execution, but it is corrupt.
"Could not load image"; error pops up.
It might be because the domain that you are trying to reach has restrictions over download policy. Check this one out, hope it helps! https://stackoverflow.com/a/8389368/2539771
import urllib
URL = "https://images-na.ssl-images-amazon.com/images/I/714tx9QbaKL.SL1500.jpg"
urllib.urlretrieve(URL, "sample.png")
from PIL import Image
img = Image.open('/home/sks/sample.png')
img.show()
I've been attempting to work at this for hours but decided to turn to the experts here on stackoverflow.
I'm trying to download an image from a url:
import urllib
originalphoto = urllib.urlretrieve(bundle.obj.url)
#originalphoto is being saved to the tmp directory in Ubuntu
This works and it saves the image in the tmp directory, but I need to modify this image by resizing it to a 250px by 250px image and then save it to a folder on my Desktop: /home/ubuntu/Desktop/resizedshots
The name of the original image is in bundle.obj.url, for example if bundle.obj.url is:
http://photographs.500px.com/kyle/09-09-201315-47-571378756077.jpg the name of the image is "09-09-201315-47-571378756077.jpg"
After the image is resized, I need to save is to this folder as 09-09-201315-47-571378756077small.jpg
As you can see, I'm adding in the word "small" to the end the file name. Once all of this is done, I would like to delete the temporary image file that was downloaded so that it doesn't take up the disk.
Any ideas on how this can be done?
Thanks
This is the definition:
def urlretrieve(url, filename=None, reporthook=None, data=None):
You can set the second argument to something you know and then do
import os
os.remove(something_you_know)
If you do not set the second argument you do this:
import urllib, os
url = 'http://photographs.500px.com/kyle/09-09-201315-47-571378756077.jpg'
file, headers = urllib.urlretrieve(url)
# do something
os.remove(file)
if os.remove does not work you still have the file open.
I have some experience with Python but none with Flask or any web development. I tried deploying my first app on PythonAnywhere using Flask. It's a very simple script and the "desktop" version works perfectly well. On the site, the image is being generated and saved to file in a static folder ('/static/').
I want the script to show the user the picture automatically once it is generated. The most important thing is that the user must be able to save it. However, when I try:
return redirect("http://www.example.com/static/image.png")
the image is being displayed properly and can be saved properly using "Save Page as". But when I right click the image and click "save image as", the file it writes is corrupted. It's not even the image (the file size is much larger). The filename is wrong too. Instead of "image.png" it saves it as "enc_text.png" ("enc_text" is the name of the function in my script.
How can I get "save image" to work?
(I don't want a solution to do with embedding the image on a blank HTML page (e.g., img src="...")
Any help is much appreciated.
EDIT
#app.route('/enc_text', methods=['POST'])
def enc_text():
text = request.form['text']
text = unidecode.unidecode(text)
filepath = os.path.join(app.config['UPLOAD_FOLDER'],'steg','enc')
filename = 'image.txt'
targetname = filename.rsplit('.', 1)[0] + '.png'
target = os.path.join(app.config['UPLOAD_FOLDER'],'steg','enc',targetname)
steg.encode(text, target) #Reads text and returns PNG file
return redirect("http://www.mysite.com/static/image.png")
(Note: steg.encode is a function I wrote)
EDIT
It seems to be only a problem with Firefox (23.0.1). The problem persists even when I restart Firefox in Safe Mode. I tried it on IE, Chrome and Safari and both "Save page" and "Save image" works fine. That's weird. I opened the "enc_text.png" using notepad and it contains the following HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
Because you're redirecting the enc_text URL to an static image - It can be weird for browser -, the better solution for your return line is:
return '<img src="http://www.mysite.com/static/image.png">'
This way you're serving a page that contains an image and it will be saved correctly. Of course the best solution is to have a full HTML page not just an img tag. So you can replace this return line with a return line of rendered HTML template.
My website allows users to upload photos to their gallery via email and it works perfectly. However, photos taken on the iPhone in portrait mode do NOT rotate correctly. I would like to rotate the photo using PIL during the "mail filtering" process. Here is the code that I am using to successfully retrieve the image from the email and save to my Django model
image = ContentFile(b64decode(part.get_payload()))
img = Photo(user=user)
filename = part.get_filename().lower()
img.img.save(filename, image)
img.save()
*Updated code that successfully rotates temp image to local dir *
image = ContentFile(b64decode(part.get_payload()))
im = Image.open(image)
tempfile = im.rotate(90)
tempfile.save("/srv/www/mysite.com/public_html/media/images/rotate.jpg", "JPEG")
img = Photo(user=user)
img.img.save('rotate.jpg', tempfile)
img.save()
Now, I'm trying to take the "temp image" and save it to my model. Unfortunately, it is not saving. Any suggestions would be greatly appreciated.
http://effbot.org/imagingbook/image.htm
clearly states that rotate() returns an new image instance.
There is nothing in the documentation about in-place operations. Or?