新年到:讓Serverless給你頭像加點裝飾

新年要到了,明天就是2020了,還沒人送你頭像裝飾?讓Serverless架構送你吧!

先分享一下地址:(http://serverless.0duzhan.com/app/new_year_add_photo_decorate/)

整體預覽:

主要功能就是選擇一個圖片,上傳自己的頭像,然后點擊生成就可以:

代碼也很簡單:

import base64, json
from PIL import Image
import uuid


def return_msg(error, msg):
    return_data = {
        "uuid": str(uuid.uuid1()),
        "error": error,
        "message": msg
    }
    print(return_data)
    return return_data


def do_circle(base_pic):
    icon_pic = Image.open(base_pic).convert("RGBA")
    icon_pic = icon_pic.resize((500, 500), Image.ANTIALIAS)
    icon_pic_x, icon_pic_y = icon_pic.size
    temp_icon_pic = Image.new('RGBA', (icon_pic_x + 600, icon_pic_y + 600), (255, 255, 255))
    temp_icon_pic.paste(icon_pic, (300, 300), icon_pic)
    ima = temp_icon_pic.resize((200, 200), Image.ANTIALIAS)
    size = ima.size

    # 因為是要圓形,所以需要正方形的圖片
    r2 = min(size[0], size[1])
    if size[0] != size[1]:
        ima = ima.resize((r2, r2), Image.ANTIALIAS)

    # 最后生成圓的半徑
    r3 = 60
    imb = Image.new('RGBA', (r3 * 2, r3 * 2), (255, 255, 255, 0))
    pima = ima.load()  # 像素的訪問對象
    pimb = imb.load()
    r = float(r2 / 2)  # 圓心橫坐標

    for i in range(r2):
        for j in range(r2):
            lx = abs(i - r)  # 到圓心距離的橫坐標
            ly = abs(j - r)  # 到圓心距離的縱坐標
            l = (pow(lx, 2) + pow(ly, 2)) ** 0.5  # 三角函數(shù) 半徑

            if l < r3:
                pimb[i - (r - r3), j - (r - r3)] = pima[i, j]
    return imb


def add_decorate(base_pic):
    try:
        base_pic = "./base/%s.png" % (str(base_pic))
        user_pic = Image.open("/tmp/picture.png").convert("RGBA")
        temp_basee_user_pic = Image.new('RGBA', (440, 440), (255, 255, 255))
        user_pic = user_pic.resize((400, 400), Image.ANTIALIAS)
        temp_basee_user_pic.paste(user_pic, (20, 20))
        temp_basee_user_pic.paste(do_circle(base_pic), (295, 295), do_circle(base_pic))
        temp_basee_user_pic.save("/tmp/output.png")
        return True
    except Exception as e:
        print(e)
        return False


def main_handler(event, context):
    try:
        print("將接收到的base64圖像轉為pic")
        imgData = base64.b64decode(json.loads(event["body"])["pic"].split("base64,")[1])
        with open('/tmp/picture.png', 'wb') as f:
            f.write(imgData)

        basePic = json.loads(event["body"])["base"]
        addResult = add_decorate(basePic)
        if addResult:
            with open("/tmp/output.png", "rb") as f:
                base64Data = str(base64.b64encode(f.read()), encoding='utf-8')
            return return_msg(False, {"picture": base64Data})
        else:
            return return_msg(True, "飾品添加失敗")
    except Exception as e:
        return return_msg(True, "數(shù)據(jù)處理異常: %s" % str(e))


def test():
    with open("test.png", 'rb') as f:
        image = f.read()
        image_base64 = str(base64.b64encode(image), encoding='utf-8')
    event = {
        "requestContext": {
            "serviceId": "service-f94sy04v",
            "path": "/test/{path}",
            "httpMethod": "POST",
            "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
            "identity": {
                "secretId": "abdcdxxxxxxxsdfs"
            },
            "sourceIp": "14.17.22.34",
            "stage": "release"
        },
        "headers": {
            "Accept-Language": "en-US,en,cn",
            "Accept": "text/html,application/xml,application/json",
            "Host": "service-3ei3tii4-251000691.ap-guangzhou.apigateway.myqloud.com",
            "User-Agent": "User Agent String"
        },
        "body": "{\"pic\":\"%s\", \"base\":\"1\"}" % image_base64,
        "pathParameters": {
            "path": "value"
        },
        "queryStringParameters": {
            "foo": "bar"
        },
        "headerParameters": {
            "Refer": "10.0.2.14"
        },
        "stageVariables": {
            "stage": "release"
        },
        "path": "/test/value",
        "queryString": {
            "foo": "bar",
            "bob": "alice"
        },
        "httpMethod": "POST"
    }
    print(main_handler(event, None))


if __name__ == "__main__":
    test()

在我的目錄下還有幾個圖片文件:

image

另外這個代碼需要依賴pillow,但是我電腦時mac的,pillow又有二進制,所以之前的項目就派上用場了:

http://serverless.0duzhan.com/app/new_year_greeting_card/

image

下載之后,直接放目錄下:

image

然后還需要有一個前端頁面,用mui,index頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>2020頭像大變樣 - 頭像SHOW - 自豪的采用騰訊云Serverless架構!</title>
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <script type="text/javascript">

        thisPic = null

        function getFileUrl(sourceId) {
            var url;
            thisPic = document.getElementById(sourceId).files.item(0)
            if (navigator.userAgent.indexOf("MSIE") >= 1) { // IE
                url = document.getElementById(sourceId).value;
            } else if (navigator.userAgent.indexOf("Firefox") > 0) { // Firefox
                url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
            } else if (navigator.userAgent.indexOf("Chrome") > 0) { // Chrome
                url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
            }
            return url;
        }

        function preImg(sourceId, targetId) {
            var url = getFileUrl(sourceId);
            var imgPre = document.getElementById(targetId);
            imgPre.aaaaaa = url;
            imgPre.style = "display: block;";
        }

        function clickChose() {
            document.getElementById("imgOne").click()
        }

        function getNewPhoto() {
            document.getElementById("result").innerText = "系統(tǒng)處理中,請稍后..."

            var oFReader = new FileReader();
            oFReader.readAsDataURL(thisPic);
            oFReader.onload = function (oFREvent) {
                var xmlhttp;
                if (window.XMLHttpRequest) {
                    // IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執(zhí)行代碼
                    xmlhttp = new XMLHttpRequest();
                } else {
                    // IE6, IE5 瀏覽器執(zhí)行代碼
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        if (JSON.parse(xmlhttp.responseText)["error"]) {
                            document.getElementById("result").innerText = JSON.parse(xmlhttp.responseText)["message"];
                        } else {
                            document.getElementById("result").innerText = "長按保存圖像";
                            document.getElementById("new_photo").aaaaaa = "data:image/png;base64," + JSON.parse(xmlhttp.responseText)["message"]["picture"];
                            document.getElementById("new_photo").style = "display: block;";
                        }
                    }
                }

                var url = " http://service-8d3fi753-1256773370.bj.apigw.tencentcs.com/release/new_year_add_photo_decorate"
                var obj = document.getElementsByName("base");
                var baseNum = "1"
                for (var i = 0; i < obj.length; i++) {
                    console.log(obj[i].checked)
                    if (obj[i].checked) {
                        baseNum = obj[i].value;
                    }
                }
                xmlhttp.open("POST", url, true);
                xmlhttp.setRequestHeader("Content-type", "application/json");
                var postData = {
                    pic: oFREvent.target.result,
                    base: baseNum
                }
                xmlhttp.send(JSON.stringify(postData));

            }

        }

    </script>
    <!--標準mui.css-->
    <link rel="stylesheet" href="./css/mui.min.css">
</head>
<body>
<h3 style="text-align: center; margin-top: 30px">2020頭像SHOW</h3>
<div class="mui-card">
    <div class="mui-card-content">
        <div class="mui-card-content-inner">
            第一步:選擇一個你喜歡的圖片
        </div>
    </div>
    <div class="mui-content">
        <ul class="mui-table-view mui-grid-view mui-grid-9">
            <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3"><label>
                <img aaaaaa="./base/1.png" width="100%"><input type="radio" name="base" value="1" checked></label></li>
            <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3"><label>
                <img aaaaaa="./base/2.png" width="100%"><input type="radio" name="base" value="2"></label></li>
            <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3"><label>
                <img aaaaaa="./base/11.png" width="100%"><input type="radio" name="base" value="11"></label></li>
            <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3"><label>
                <img aaaaaa="./base/4.png" width="100%"><input type="radio" name="base" value="4"></label></li>
            <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3"><label>
                <img aaaaaa="./base/5.png" width="100%"><input type="radio" name="base" value="5"></label></li>
            <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3"><label>
                <img aaaaaa="./base/6.png" width="100%"><input type="radio" name="base" value="6"></label></li>
            <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3"><label>
                <img aaaaaa="./base/12.png" width="100%"><input type="radio" name="base" value="12"></label></li>
            <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3"><label>
                <img aaaaaa="./base/8.png" width="100%"><input type="radio" name="base" value="8"></label></li>
            <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3"><label>
                <img aaaaaa="./base/3.png" width="100%"><input type="radio" name="base" value="3"></label></li>
        </ul>
    </div>
</div>
<div class="mui-card">
    <div class="mui-card-content">
        <div class="mui-card-content-inner">
            第二步:上傳一張你的頭像
        </div>
        <div>
            <form>
                <input type="file" name="imgOne" id="imgOne" onchange="preImg(this.id, 'photo')" style="display: none;"
                       accept="image/*">
                <center style="margin-bottom: 10px">
                    <input type="button" value="點擊此處上傳頭像" onclick="clickChose()"/>
                    <img id="photo" aaaaaa="" width="300px" , height="300px" style="display: none;"/>
                </center>
            </form>
        </div>
    </div>
</div>

<div class="mui-card">
    <div class="mui-card-content">
        <div class="mui-card-content-inner">
            第三步:點擊生成按鈕獲取新年頭像
        </div>
        <div>
            <center style="margin-bottom: 10px">
                <input type="button" value="生成新年頭像" onclick="getNewPhoto()"/>
                <p id="result"></p>
                <img id="new_photo" aaaaaa="" width="300px" , height="300px" style="display: none;"/>
            </center>
        </div>
    </div>
</div>

<p style="text-align: center">
    本項目自豪的<br>通過Serverless Framework<br>搭建在騰訊云SCF上
</p>

</body>
</html>

最后再來一個Yaml:

new_year_add_photo_decorate:
  component: "@serverless/tencent-scf"
  inputs:
    name: myapi_new_year_add_photo_decorate
    codeUri: ./new_year_add_photo_decorate
    handler: index.main_handler
    runtime: Python3.6
    region: ap-beijing
    description: 新年為頭像增加飾品
    memorySize: 128
    timeout: 5
    events:
      - apigw:
          name: serverless
          parameters:
            serviceId: service-8d3fi753
            environment: release
            endpoints:
              - path: /new_year_add_photo_decorate
                description: 新年為頭像增加飾品
                method: POST
                enableCORS: true
                param:
                  - name: pic
                    position: BODY
                    required: 'FALSE'
                    type: string
                    desc: 原始圖片
                  - name: base
                    position: BODY
                    required: 'FALSE'
                    type: string
                    desc: 飾品ID

myWebsite:
  component: '@serverless/tencent-website'
  inputs:
    code:
      aaaaaa: ./new_year_add_photo_decorate/web
      index: index.html
      error: index.html
    region: ap-beijing
    bucketName: new-year-add-photo-decorate

還有還有我開源的git地址:

https://github.com/anycodes/ServerlessPractice?


image
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,836評論 6 540
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,275評論 3 428
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,904評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,633評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,368評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,736評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,740評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,919評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,481評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,235評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,427評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,968評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,656評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,055評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,348評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,160評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,380評論 2 379

推薦閱讀更多精彩內容