unable to use PIL in django view function - python

I am trying to make a function that makes thumbnail of an image but I am unable to open the image file.
def create_thumbnail(request):
slug = 'yftguhjkn'
post = get_object_or_404(Post, slug=slug)
if post:
markdownify = import_string(MARKDOWNX_MARKDOWNIFY_FUNCTION)
content = BeautifulSoup(markdownify(post.content), "html5lib")
try:
img_link = content.findAll('img')[0].get('src')
print(img_link)
filename = img_link.split('/')[-1]
filename = filename.split('.')[0]
file_path = settings.MEDIA_URL + settings.DRACEDITOR_UPLOAD_PATH + post.author.username + '/' + filename + '.jpg'
print (file_path)
#im = Image.open(img_link)
im = Image.open(file_path)
print (im.size)
except:
img_link = 'http://howtorecordpodcasts.com/wp-content/uploads/2012/10/YouTube-Background-Pop-4.jpg'
return HttpResponse(img_link)
But it is going to except statement. Can someone please tell me how to fix it.
def create_thumbnail(request):
slug = 'yftguhjkn'
post = get_object_or_404(Post, slug=slug)
if post:
markdownify = import_string(MARKDOWNX_MARKDOWNIFY_FUNCTION)
content = BeautifulSoup(markdownify(post.content), "html5lib")
#try:
img_link = content.findAll('img')[0].get('src')
print(img_link)
filename = img_link.split('/')[-1]
filename = filename.split('.')[0]
file_path = settings.MEDIA_URL + settings.DRACEDITOR_UPLOAD_PATH + post.author.username + '/' + filename + '.jpg'
print (file_path)
im = Image.open(file_path)
print (im.size)
#except:
#img_link = 'http://howtorecordpodcasts.com/wp-content/uploads/2012/10/YouTube-Background-Pop-4.jpg'
return HttpResponse(file_path)

I think the Pillow need a correct path (full path) from the image to open.
im = Image.open(file_path)
the commond output of settings.MEDIA_URL is /media/ right?
so, you need to file_path is the full path, eg:
/home/myuser/myenv/myproject/media/images/uploads/2017/05/29/foobar.png
If your settings.MEDIA_ROOT is:
/home/myuser/myenv/myproject/media
You can doing with:
os.path.join(settings.MEDIA_ROOT, settings.DRACEDITOR_UPLOAD_PATH, image_name)
# example:
'/home/myuser/myenv/myproject/media' + 'images/uploads/2017/05/29/' + 'foobar.png'
you can also using BASE_DIR for absolute dir.

Related

Django: Downloaded image won't open

I am currently working on a Django app that allows me to download an image while only storing the image as a temporary file. My Django app is running on a server while I am accessing the website through a local windows machine. While I am able to download the image, the file will not open. For example, Windows Photos says that "It appears we don't support this file format". Is there something wrong with the code that would cause this problem?
Views.py
def download_png(request, study):
Names(study) #Function to retrieve (name) variable
Retrieve(study) #Function to retrieve (data) variable
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
pngfilename = str(name) + "_" + str(current_time) + ".png"
filepath = BASE_DIR + '/polls/graphics/' + pngfilename
temp, filepath = tempfile.mkstemp(suffix='.png')
with open(temp, 'w') as f:
f = df2img.plot_dataframe(data)
df2img.save_dataframe(fig=f, filename=filepath)
response = HttpResponse(temp, content_type=mimetypes.guess_type(filepath))
response['Content-Disposition'] = "attachment; filename=%s" % pngfilename
return response
Update 06/30/22:
Thank you for all the help. It turns out it is better to use FileResponse rather than HttpResponse when downloading a file Here's what the updated code looks like:
def download_png(request, study):
Names(study)
Retrieve(study)
pngfilename = str(name) + "_" + str(current_time) + ".png"
mime_type, _ = mimetypes.guess_type(pngfilename)
fig = df2img.plot_dataframe(data)
df2img.save_dataframe(fig=fig, filename=pngfilename)
response = FileResponse(open(pngfilename, 'rb'), content_type=mime_type)
response['Content-Disposition'] = "attachment; filename=%s" % pngfilename
os.remove(pngfilename)
return response

As I send list link to requests.get (). content Python?

I am sending an extracted list with xpath but it doesn't work with xpath
it works like this URL1
url = ['http://images/productos/on-line/items/large/nb/de/nbdell1tc73.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_1.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_2.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_3.jpg'
]
it does not work URL2
url = sel.xpath('//section[#class="product-images js-product-images-container"]//img/#src')
result url.path
'url': ['http://images/productos/on-line/items/large/nb/de/nbdell1tc73.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_1.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_2.jpg',
'http://images/productos/on-line/items/large/nb/de/nbdell1tc73_3.jpg'],
this code recepte the url
i = 0
for url22 in url:
try:
imagen_content = requests.get(url22).content
image_file = io.BytesIO(imagen_content)
imagen = Image.open(image_file).convert('RGB')
path = './imagenes/' + '_' + str(i) + '.jpg'
with open(path, 'wb')as f:
imagen.save(f, "JPEG", quality=85)
except Exception as ex:
print(ex)
print("ERROR")
i += 1
With the first url it works, with the second one it doesn't.
How do I make it work with url2?
it turned out, I need to put url.get () url22.get()
i = 0
for url22 in url:
try:
imagen_content = requests.get(url22.get()).content
image_file = io.BytesIO(imagen_content)
imagen = Image.open(image_file).convert('RGB')
path = './imagenes/' + '_' + str(i) + '.jpg'
with open(path, 'wb')as f:
imagen.save(f, "JPEG", quality=85)
except Exception as ex:
print(ex)
print("ERROR")
i += 1

Read all images from subfolder, resize them and save them with their original name in Python?

I want to read all images from a different subfolder, resize them and save them with their original name. However, I get the error shown below. How do I fix this error?
example code:
from PIL import Image
import os
size = (112, 112)
def resize_img(path,dest_path):
name_list = []
label_list = []
resized_list = []
if not os.path.exists(dest_path):
os.makedirs(dest_path)
folder_list = os.listdir(path)
for num_imgs,folder in enumerate(folder_list):
print(str(num_imgs) + " : " + folder)
files_path = path + "/" + folder
image_list = os.listdir(files_path)
name_list.append(folder)
for image_name in image_list:
image_path = path + "/" + folder + "/" + image_name
print(image_path)
img = Image.open(image_path)
label_list.append(img)
for image in label_list:
image = image.resize((112, 112))
resized_list.append(image)
for (i,new) in enumerate (resized_list):
new.save('{}{}{}'.format(dest_path+'/'+str(label_list)+str('_'), i+1, '.jpg'))
resize_img('C:/Users/aunglay/PycharmProjects/FR_using_cnn/Face_database',
'C:/Users/aunglay/PycharmProjects/FR_using_cnn/resized_images')
Error appeared:
Traceback (most recent call last):
File "C:/Users/aunglay/PycharmProjects/FR_using_cnn/smaple2.py", line 30, in <module>
'C:/Users/aunglay/PycharmProjects/FR_using_cnn/resized_images')
File "C:/Users/aunglay/PycharmProjects/FR_using_cnn/smaple2.py", line 27, in resize_img
new.save('{}{}{}'.format(dest_path+'/'+str(label_list)+str('_'), i+1, '.jpg'))
File "C:\Users\aunglay\Anaconda3\envs\tensorflow_env\lib\site-packages\PIL\Image.py", line 2099, in save
fp = builtins.open(filename, "w+b")
OSError: [Errno 22] Invalid argument: 'C:/Users/aunglay/PycharmProjects/FR_using_cnn/resized_images/[<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=64x64 at 0x2D7ACFD508>]_1.jpg'
The problem seems to be in the last line of the code:
new.save('{}{}{}'.format(dest_path+'/'+str(label_list)+str('_'), i+1, '.jpg'))
Specifically, label_list will be a list of image objects and will not contain the name of the image you just read. Plus, I think the last two for loops are not necessary. You could change the code:
for image_name in image_list:
image_path = path + "/" + folder + "/" + image_name
print(image_path)
img = Image.open(image_path)
label_list.append(img)
for image in label_list:
image = image.resize((112, 112))
resized_list.append(image)
for (i,new) in enumerate (resized_list):
new.save('{}{}{}'.format(dest_path+'/'+str(label_list)+str('_'), i+1, '.jpg'))
to:
for image_name in image_list:
image_path = path + "/" + folder + "/" + image_name
print(image_path)
img = Image.open(image_path)
label_list.append(img)
resized_list.append(img.resize((112, 112)))
resized_list[-1].save(dest_path+'/'+image_name+'.jpg')
And that should implement what you describe.
edit:
concerning what was asked in the comments:
def resize_img(path,dest_path):
name_list = []
label_list = []
resized_list = []
folder_list = os.listdir(path)
for num_imgs,folder in enumerate(folder_list):
if not os.path.exists(dest_path+'/'+folder):
os.makedir(dest_path+'/'+folder)
print(str(num_imgs) + " : " + folder)
files_path = path + "/" + folder
image_list = os.listdir(files_path)
name_list.append(folder)
for image_name in image_list:
image_path = path + "/" + folder + "/" + image_name
print(image_path)
img = Image.open(image_path)
label_list.append(img)
resized_list.append(img.resize((112, 112)))
resized_list[-1].save(dest_path+'/'+folder+'/'+image_name+'.jpg'
This should implement what you were describing. You need to call os.mkdir() for each of the sub-folders you want to create, thus it has to be inside the first for loop.

How to set the content type of an image before storing it to blobstore?

I'm trying to rotate and save the image to GCS with the below code.
img = images.Image(blob_key=image.blob)
img.rotate(270)
t = img.execute_transforms(output_encoding=images.PNG)
filename = '/' + UploadHandler.get_gs_bucket_for_images() + 'blobstore_demo.png'
with gcs.open(filename, 'w') as f:
f.write(t)
blobstore_filename = '/gs' + filename
key = blobstore.create_gs_key(blobstore_filename)
But when I try to view the file using GAE's blostore Viewer, I get an encoded image. That is, the content-type for that blob is not set to image/png. So how I managed to set the content-type?
You can define your image mimetype, just edit yor code this way:
img = images.Image(blob_key=image.blob)
img.rotate(270)
t = img.execute_transforms(output_encoding=images.PNG)
filename = '/' + UploadHandler.get_gs_bucket_for_images() + 'blobstore_demo.png'
mimetype = 'image/png'
with gcs.open(filename,'w', content_type=mimetype) as f:
f.write(t)
blobstore_filename = '/gs' + filename
key = blobstore.create_gs_key(blobstore_filename)

Google contacts. GetPhoto

We want to import contacts photos from google API.
Following code was working for me.
for email, name, entry in feed:
photo = client.GetPhoto(entry)
if photo:
fname = str(uuid.uuid4()) + '.jpg'
image_file = open(dname + '/' + fname, 'wb')
image_file.write(photo)
image_file.close()
result[email] = '/media/import/%s/%s' % (dir, fname)
Now, for some reasons, we get in files atom feed copy. So method GetPhoto no working.
Any ideas, why it happened and what is current way to retrieve contacts photo?
Here is work around google API changes. Now we're using direct requests to API.
for email, name, entry in feed:
photo_link = e.GetPhotoLink()
if photo_link:
request = http.request(
'GET',
photo_link.href,
headers={
'Authorization':'OAuth %s' % client.current_token.access_token
}
)
if request.status == 200:
photo = str(request.read())
fname = str(uuid.uuid4()) + '.jpg'
image_file = open(dname + '/' + fname, 'wb')
image_file.write(photo)
image_file.close()
result[email] = '/media/import/%s/%s' % (tid, fname) #str(photo.href) #

Categories

Resources