20200111


Google Image search X Python ¶

Dear name 超級好聽,收錄在 Palette 裡


起因 ¶

再找圖片的時候,由於要一直拉圖片上傳到 google image search 實在是太麻煩了

所以寫了一個小小的網站,可以上傳圖片,然後點擊圖片,就會自動打上傳圖片完成,並開啟新網址

所以不用再一直拉圖片上 google image search 了

這次用了 Flask 來當 server

Flask ¶

Flask is a lightweight WSGI web application framework.

選用 Flask 是因為之後可能要用到,所以就先學了一下

一樣推薦用 virtualenv 來安裝

pip install Flask

這樣就安裝完了

最簡單的小網站

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

env FLASK_APP=hello.py flask run

Source: Flask

Google Image Search ¶

這基本上是最難的部分,有夠麻煩

原本是想說用 google search 的網址,後面加上東西這樣

這個的方法

https://www.google.com/searchbyimage?site=search&sa=X&image_url=YOUR_IMAGE_URL

結果發現這只能用於圖片在線上

然後找到這個方法 Link

讀取圖片,encode,然後上傳,就可以得到網址了

Forend ¶

前端基本上是根據這個去改的 Link

不過這個寫法有點舊了,我改成 ES6 的方法,然後用 map 去處理原本的迴圈

function handleFileSelect(evt) {
    const files = evt.target.files; // FileList object
    Array.from(files).map(file => setPicture(file));
    document.getElementById("browseFile").style.display = "none";
}

function setPicture(file) {
    if (file.type.match("image.*")) {
        let reader = new FileReader();

        // Closure to capture the file information.
        reader.onload = (theFile => {
        return function(e) {
            let img = document.createElement("img");
            img.className = "thumb";
            img.src = e.target.result;
            img.title = escape(theFile.name);

            let span = document.createElement("span");
            span.addEventListener("click", handleDoSearch, false);
            span.appendChild(img);

            document.getElementById("list").insertBefore(span, null);
            };
        })(file);

        // Read in the image file as a data URL.
        reader.readAsDataURL(file);
    }
}

上傳圖片的圖示,改成用 bootstrap 比較好看

這裡使用了 ajax 去傳遞資料

果然我還是活在舊時代的啊,現在還在用 jQuery

不過也是我不知道現在和後端連線都是怎麼連的

看來該找時間研究研究了

可是前端好麻煩啊

反正取得網址之後在新視窗開啟,這樣就結束了

jQuery

因為上傳的圖片會被轉換成 base64 資料

所以會是一長串 string 傳到後端

然後試了各種 decode, encode 方法,還是沒辦法把圖片上傳

所以決定不要想辦法 encode 了

直接把 base64 轉成圖片,再讀取一次,再把檔案刪掉

image_result = open('baseimage.jpg', 'wb')
image_result.write(base64.b64decode(file_contents[1]))
multipart = {'encoded_image': (filePath, open("baseimage.jpg", 'rb')), 'image_content': ''}

Source1: python-open-requires-full-path

Source2: typeerror-expected-bytes-like-object-not-str


Github ImageSearch ¶


這東西大概搞了一天吧

沒辦法,大部分的東西都忘光光了

都要重新複習一次

下次更新點別個吧

是說三期會員禮已經有人收到了,好想要啊

但是好貴啊,都要 3000 左右

過完年要好好認真找工作了

不然養不起啊 QQ