Uploading profile image with twitter api and python - python

I want to upload an image from my hard drive, using an html form:
Image file: <input name="imageupload" id="imageupload" type="file" />
Then I upload it to twitter with:
image=self.request.get('imageupload')
image2=base64.b64encode(image)
twitapi.Update_profile_image(image=image2)
given twitapi.Update_profile_image:
def Update_profile_image(self,image):
if not self._oauth_consumer:
raise TwitterError("The twitter.Api instance must be authenticated.")
url = '%s/account/update_profile_image.json' % (self.base_url)
data = {'image':image}
json = self._FetchUrl(url, post_data=data)
data = self._ParseAndCheckTwitter(json)
return data
Given _FetchUrl from twitter-api
I always get
TwitterError: There was a problem with your picture. Probably too big.
Any ideas whee it comes from? Thanks!

To submit ah image correctly via a form, you have to include
enctype="multipart/form-data"
eg
<form enctype="multipart/form-data" action='/' method="POST">

Twitter RESTful API Document is not correct.
Do NOT encode image binary to base64!
Remove base64 encode section from your source.
If you encode image binary to base64 string, twitter api says
"... was a problem with your picture probably too big. (...) (code 131)"

As per the documentation, your image:
Must be a valid GIF, JPG, or PNG image of less than 700 kilobytes in size.
So make sure your image fits within these constraints. Maybe you need to scale down your image, or convert it to a different format.
If that doesn't work, try uploading another very tiny image that meets the constraints above. At least you can then verify whether or not the problem lays with the particular image you are using.

Perhaps the image you are receiving via the form upload is already base64 encoded ?
You are then applying a double encoding which could confuse the validation on the twitter server side because it would be unable to find a typical image header in your uploaded file.

Related

The extension in image url is different from actual format

I downloaded an image from a url such as "https://www.xxxx.com/filename.jpeg. I expected that that image is a jpeg image whose format is acceptable for Computer Vision Annotation Tool (CVAT). However, it was saved as filename.heif or filename.jpeg.heif, so it causes an error when I tried to create a task with that image because heif format is not acceptable in CVAT. (CVAT automatically downloads images and create a task once I put image urls and submit them.)
I usually put more than 1000 image urls to create a task, and it is really hard to find invalid url or image among them.
Is there any way to find the "actual format" only by looking at the image url? Or can I just skip invalid urls in CVAT?
Thank you.

Get original image url from base64 Image String using Python?

Wondering can someone point me in the right direction on how to convert base64 image string to its original image URL.
My code is scraping top 5 news from google based on my search string.
Images are in one big massive base64 string. Images are printing ok on my outlook email (my code extract the news and send out an email in outlook) but when I forward that email on to different email account can't see any image but a message The linked image cannot be displayed. The file may have been moved, renamed or deleted. Just to check that, I copied the image from my outlook email and tried to paste on word document; all I can see is an empty box but no image.
any advice, please?
You can't get a URL from those. Those base64 encoded strings are fully embedded images. You could base64 decode them and save it to a file or just take the base64 encoded string an attach it to another image tag like in the incoming email.
If you have some specific code I could be of more help.

How does Facebook share image base64 from Google App Engine

Im working with Google App Engine Project and I want use facebook share like this.
http://i.stack.imgur.com/uz52n.png
Im already read this
How does Facebook Sharer select Images and other metadata when sharing my URL?
but GAE cant upload physical Image, all image store in blob property in database as base64 so facebook share cant get the image :(
anyone had another idea for this problem ??
Facebook reads the og:image meta to resolve the image from your webpage. og:image don't allow data-URI image (base64 encoded).
You have to provide an image url in og:image, but with that url, you can make a workaround to simulate the behaviour of a direct image resolution and get the image from your appengine database.
This is a solution in python using Django, but the concept works for everything. The name of the image is here "key.png" where key is the key of the object containing the base64 stored image.
First, add an url to the list of django urls for your image resolution:
(r'^image/(?P<key>[^\.^/]+)\.png$', 'yourapp.views.image'),
Then in your views, get the key from the url, retrieve your object, base64 decode and send it back with the correct mimetype:
import base64
def image(request, key):
# get your object from database
f = YourImageObject.get(key)
# f.pic is the base64 encoded image
pic = f.pic[len("data:image/png;base64,"):] # remove the header
# base64 decode and respond with correct mimetype
return HttpResponse(base64.b64decode(pic), mimetype="image/png")

How do I display a PIL Image object in a template?

If a user uploads an image, and I resize it using PIL, I get a PIL Image object.
How do I display a PIL Image file in a template, before it has been saved to the database? Can it even be passed in as an image and rendered?
For a limited set of browsers, you can base64 encode the image and use inline images. See Embedding Base64 Images.
A solution that works for all browsers is an image tag referencing a view that returns the image.
[update]
All I want is for the user to submit the original image, and then be prompted by another form to input a caption for the image (with the resized image to the left of the caption field). Then when the user hits "submit" the image and the caption get saved in a model instance.
Well... When you use <img src="foo">, foo is always retrieved by a GET perhaps that is why it is not working - request.FILES will not be available in a GET request. If you open firebug or the chrome debug toolbar, in the network tab, you will see the POST request with the uploaded image and after that a GET request to fetch the image.
You have to save the image somewhere between both steps.
how else could i save it? I would love for it to be temporary. Do you think there's a really easy way to do this, or should I go look into those options?
Popular choices are redis and memcached. You can think of them as giant shared python dict with an expire date. If the images are small, like an avatar, you can also save the image data in a session variable.
Yes and no.
Yes, you can put the images as raw Base64 data. Here's a little script you can use to test this:
import Image
import base64
import StringIO
output = StringIO.StringIO()
im = Image.open("test.png") # Your image here!
im.save(output, format='PNG')
output.seek(0)
output_s = output.read()
b64 = base64.b64encode(output_s)
open("test.html","w+").write('<img src="data:image/png;base64,{0}"/>'.format(b64))
However, this is a really bad idea. With multiple thumbnails, your single HTML page might be 10MB+.
What you really should be doing is using a separate Django view to return images from PIL objects as PNG files, and then referencing that view in the img href attributes on your page.
You can embed base64 encoded images into an tag. So you could convert PIL image to base64 and then display it.
from PIL import Image
import StringIO
x = Image.new('RGB',(400,400))
output = StringIO.StringIO()
x.save(output, "PNG")
contents = output.getvalue().encode("base64")
output.close()
contents = contents.split('\n')[0]
Then show with:
<img src="data:image/png;base64,' + contents + ' />
Look to an example output.

Including a dynamic image in a web page using POST?

I have written a CGI script that creates an image dynamically using GET data. To include this image in my webpage, I am using the following code:
<img src="image.py?text=xxxxxxxxxxxxxx">
The problem is that I expect in the future the "text" field will get very long and the URL will become too large. From Googling around there doesn't seem to be a fixed limit on URL length (ie. depends on the browser, server, proxy, etc.) Is there a better way to do this?
If it matters, I am working with Django and Python and I cannot use any client-side scripting (ie. JavaScript).
Cheers,
Ben
Store the text somewhere (e.g. a database) and then pass through the primary key.
This will get you an Image as the result of a POST -- you may not like it
Put an iFrame where you want the image and size it and remove scrollbars
Set the src to a form with hidden inputs set to your post parameters and the action set to the URL that will generate the image
submit the form automatically with JavaScript in the body.onload of the iFrame's HTML
Then, either:
Serve back an content-type set to an image and stream the image bytes
or:
store the post parameters somewhere and generate a small id
serve back HTML with an img tag using the id in the url -- on the server look up the post parameters
or:
generate a page with an image tag with an embedded image
http://danielmclaren.net/2008/03/embedding-base64-image-data-into-a-webpage
Putting together what has already been said, how about creating two pages. First page sends a POST request when the form is submitted (lets say to create_img.py) with a text=xxxxxxx... parameter. Then create_img.py takes the text parameter and creates an image with it and inserts it (or a filesystem reference) into the db, then when rendering the second page, generate img tags like <img src="render_img.py?row_id=0122">. At this point, render_img.py simply queries the db for the given image. Before creating the image you can check to see if its already in the database therefore reusing/recycling previous images with the same text parameter.
img's use GET. You'll have to come up with another mechanism. How about calling the same functionality in image.py and saving the file as a temp file which you ref in the img tag? Or how about saving the value of text in a db row during the rendering of this img tag and using the row_id as what you pass into the image.py script?
You may be able to mitigate the problem by compressing the text in the get parameter.
From the link below it looks like you'll be fine for a while ;)
http://www.boutell.com/newfaq/misc/urllength.html
If you're using django, maybe you can do this via a template tag instead?
Something like:
<img src="{% create_image "This is the text that will be displayed" %}">
The create_image function would create the image with a dummy/random/generated filename, and return the path.
This avoids having to GET or POST to the script, and the images will have manageable filenames.
I can see some potential issues with this approach, I'm just tossing the idea out there ;)
OK, I'm a bit late to the party, but you could use a mix of MHTML (for IE7 and below) and the data URI scheme (for all other modern browsers). It does require a bit of work on both client and server but you can ultimately end up with
newimg.src = 'blah';
The write-up on how to do this is at http://gingerbbm.com/?p=127.

Categories