0

I want to make a webpage with Flask which enables me to search images according to some keywords and return two relevant images in the webpage.

And, assume the keyword is 'Steve jobs' and these images that are related to 'Steve jobs' will be scraped by Google Search and stored in a file called 'Steve jobs'.

But I still cannot display images from my file and return a blank page.

hello.py

@app.route("/about",methods=['GET', 'POST'])
def about():
    ...
    DIR = os.path.join(os.getcwd())
    DIR = os.path.join(DIR, query.split()[0])
    ...
    def show_index(): 
        for i,(img,Type) in enumerate(ActualImages[:2]):
            try:
                 req = urllib.request.Request(img, headers=header)
                 raw_img = urllib.request.urlopen(req).read()
                 cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1
                 print(cntr)

                 if len(Type)==0:
                     f = open(os.path.join(DIR,image_type + "_"+ str(cntr)+".jpg"),'wb')
                 else:
                      f = open(os.path.join(DIR,image_type + "_"+ str(cntr)+"."+Type),'wb')
                      f.write(raw_img)
                      f.close()

            except Exception as e:
                  print('>>> Could not load: '+img)
                  print(e)

        return f

    return render_template('about.html', f = f)

about.html

<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body>
    <img src="{{f}}" alt="f">
</body>
</html>
Nimantha
  • 6,405
  • 6
  • 28
  • 69
EricLee
  • 3
  • 4

1 Answers1

0

A typical HTML image tag looks like so:

<img src="/path/image.gif" alt="My Image"/>

As you can see, the src attribute contains a URL telling the browser where to find the image. It will go off and download the image from there. It doesn't contain the image itself. Your code appears to be trying to load the image file's content into the HTML, and that won't work.

(Note - it is possible to directly embed images into HTML, but it's pretty unusual, so I won't talk about that.)

Given that, what you need to is to put the images somewhere, and serve and refer to them as per the answer to How do i link to images not in Static folder in flask.

brunns
  • 2,689
  • 1
  • 13
  • 24