基于Python实现网页版之去文档图片水印

基于Python实现网页版去文档图片水印

Python可以用OpenCV去除图片水印,但如何结合web框架去实现网页版去水印,带着这样的疑问,我搜索研究了一下,发现是完全可以实现的,而且考虑到部署服务器,也是可以实现的,这里就不详细说明了。本文采用Pycharm软件。

基于Flask框架实现网页上传图片,执行效果:

打开网页输入以下网址:127.0.0.1:5000,这是来源于后面代码app.run(host='0.0.0.0', port=5000, debug=True)。

代码解析:

(1)Flask框架搭建

新建qushuiyin.py文件,在该文件下输入以下代码。

from flask import Flask, render_template, request, redirect, url_for, make_response, jsonify
from werkzeug.utils import secure_filename
import os
import cv2
import time
import numpy as np
from PIL import Image

from datetime import timedelta

# 设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


app = Flask(__name__)
# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)


# @app.route('/upload', methods=['POST', 'GET'])
@app.route('/', methods=['POST', 'GET'])  # 添加路由
def upload():
    if request.method == 'POST':
        f = request.files['file']

        if not (f and allowed_file(f.filename)):
            return jsonify({"error": 1001, "msg": "请检查上传的图片类型,仅限于png、PNG、jpg、JPG、bmp"})

        user_input = request.form.get("name")

        basepath = os.path.dirname(__file__)  # 当前文件所在路径

        upload_path = os.path.join(basepath, './static/photo', secure_filename(f.filename))  # 注意:没有的文件夹一定要先创建,不然会提示没有该路径
        f.save(upload_path)

        return render_template('REpicture_ok.html', val1=time.time())

    return render_template('REpicture.html')


if __name__ == '__main__':
    # app.debug = True
    app.run(host='0.0.0.0', port=5000, debug=True)

(2)REpicture_ok.html和Repicture.html搭建

在当前目录下新建Repicture_ok.html和Repicture.html空白文件,输入以下代码。

#REpicture.html
<head>
    <meta charset="UTF-8">
    <title>图片右下角去水印</title>
</head>
<body>
    <h1>请上传图片文件</h1>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file" style="margin-top:20px;"/>
        <br>
        <input type="submit" value="去水印" class="button-new" style="margin-top:15px;"/>
    </form>
</body>
</html>
#REpicture_ok.html
<head>
    <meta charset="UTF-8">
    <title>图片右下角去水印</title>
</head>
<body>
    <h1>请上传图片文件</h1>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file" style="margin-top:20px;"/>
        <br>
        <input type="submit" value="去水印" class="button-new" style="margin-top:15px;"/>
    </form>
    <img src="{
   
   { url_for('static', filename= './photo/result.jpg',_t=val1) }}" width="400" height="400" alt="你的图片被外星人劫持了~~"/>
</body>
</html>

注意:filename= './photo/result.jpg',路径要描述准确,否则会报错。

(3)实现文本文档去水印

(1)首先在qushuiyin.py里import下增加一个函数定义图像处理代码:

# 图像矩阵处理
def levelsdeal(img, black, white):
  if white > 255:
     white = 255
  if black < 0:
     black = 0
  if black >= white:
     black = white - 2
  img_array = np.array(img, dtype=int)
  cRate = -(white - black) / 255.0 * 0.05
  rgb_diff = img_array - black
  rgb_diff = np.maximum(rgb_diff, 0)
  img_array = rgb_diff * cRate
  img_array = np.around(img_array, 0)
  img_array = img_array.astype(int)
  return img_array

(2)其次在 f.save(upload_path)下接着输入以下代码:

img = Image.open(upload_path)
img = levelsdeal(img, 110, 160)
img_res = Image.fromarray(img.astype('uint8'))
img_res.save(upload_path)
img_res = cv2.imread(upload_path)
cv2.imwrite(os.path.join(basepath, './static/photo', 'result.jpg'), img_res)
os.remove(os.path.join(basepath, './static/photo', secure_filename(f.filename)))

说明:

1. img = levelsdeal(img, 110, 160)两个常数是可以修改的;

2.'./static/photo'注意路径;

3.过程中会产生几个文件,使用os.remove进行删除操作。

总结:

文本图片去水印项目已经很成熟了,网上可以找到很多实例,但结合时下服务器的应用还有待开拓,所以本文还有很多拓展空间,留待后面慢慢完善。

 

Guess you like

Origin blog.csdn.net/Crazydoubao/article/details/115749603