Automatic generation of local markdown files | batch compression of pictures and conversion to base64 format | farewell to the drawing bed server | blog artifact

1, Project introduction

Problem source

Every time a document in markdown format is written locally, you want to upload it to the blog website, but the local image cannot be directly copied to the blog page of the website. Each image needs to click upload again, and then upload the local file. In fact, you can also buy a picture bed to solve it. However, you are shy in your pocket and still don't want to save the pictures to someone else's server. Therefore, I want to insert base64 pictures into the markdown document to complete the convenient upload of blog posts.

Target functions, problems and Solutions

Therefore, to realize the function:

  • Convert the existing markdown text into a markdown with base64 image coding inserted

To realize the above functions, there are several problems:

  • base64 code is too long, which is not conducive to the viewing of blog posts
  • base64 encoding is too long, resulting in huge text content

Solve the problem in the following two ways:

  • For the problem that base64 coding is too long, which is not conducive to viewing blog posts.

  • base64 encoding is too long, resulting in huge text content

    • Solution: compress the image size, and the corresponding base64 encoding will also be compressed (of course, it will also sacrifice the clarity of the image)

To sum up, I want to achieve:

Through a python program, the local markdown file and the local picture associated with the file are generated into a new markdown file with base64 encoding only (the viewing effect is the same as the original file and does not depend on the original file at all)

2, Introduction to source program ideas

Idea:

Search the image format in the source file through regular expression, and then replace it with base64 format. base64 encoding is appended at the end of the file and saved as a new file.

code snippet

Import dependent package

from PIL import Image
import os
import base64
import re

Function: image to base64

#Convert the picture with address to base64 string
def phtot_base64(address):
    with open(address,"rb") as photo:
        pb=base64.b64encode(photo.read())
        return str(pb)[2:-1]

Function: get the size of the file in KB

# Get file size: KB
def get_size(file):
    size = os.path.getsize(file)
    return size / 1024

Functions: compressing images

def compress_image(infile_path, outfile_path, aim_size, step=10, quality=80):
    """Do not change the size of the picture and compress it to the specified size
    :param infile: Compress source files
    :param outfile: Compressed file storage address
    :param aim_size: Compress the target, KB
    :param step: Compression ratio per adjustment
    :param quality: Initial compression ratio
    :return: Compressed file address, compressed file size
    """
    o_size = get_size(infile_path)
    # If the current picture size is smaller than the compression target size
    if o_size <= aim_size:
        im = Image.open(infile_path)
        im = im.convert('RGB')  # To save as a jpg file, convert the image to rgb
        im.save(outfile_path, quality=quality)  # Save compressed image
        print("The picture has been compressed!")
        return infile_path
    
	# If the current picture size is larger than the compression target size
    while o_size > aim_size:
        im = Image.open(infile_path)
        im = im.convert('RGB')  # To save as a jpg file, convert the image to rgb
        im.save(outfile_path, quality=quality)  # Save the compressed image
        if quality - step < 0:
            break
        quality -= step
        o_size = get_size(outfile_path)

    print("The picture has been compressed!")
    return outfile_path

The specific implementation process can be discussed next time. The code is open source. Welcome to visit and star my gitee project markdown image to base64.

3, Effect display and instructions

The file directory is as follows:

Let's now format [test.md]. Pictures in pic folder are as follows and have been referenced by [test.md]:

Execute [img_to_base64.py]!!!, You need to enter the original markdown path and how large you want to compress the picture. The operation and printing results are as follows:

(base) PS E:\mydoc\done\2021\summer\md_img2base64_project\tests> python .\img_to_base64.py

******************************
Please enter a target markdown File address:
"E:\mydoc\done\2021\summer\md_img2base64_project\tests\test.md"
******************************

******************************
Please enter the maximum volume allowed for compressed pictures(Company: KB): 100
******************************

******************************
picture:[pic/image-20210422132634431.png]Read!

original image  base64 Text length is:28816
 The picture has been compressed!
Compressed image base64 Text length is:28816
******************************

******************************
picture:[pic/image-20210422132812199.png]Read!

original image  base64 Text length is:233024
 The picture has been compressed!
Compressed image base64 Text length is:21488
******************************


******************************
File image conversion succeeded!
******************************
Please press any key to continue. . .

Then the file directory is programmed as follows:

[compare two markdown texts]:

Original document:

![image-20210422132634431](pic/image-20210422132634431.png)

Aston faza



### Method scholar doctor

/SA dada



$\sigma$

![image-20210422132812199](pic/image-20210422132812199.png)

Converted file:

![image-20210422132634431][Fig1]

Aston faza



### Method scholar doctor

/SA dada



$\sigma$

![image-20210422132812199][Fig2]

****************************************************************************************************
  
****************************************************************************************************
  
****************************************************************************************************

[Fig1]:data:image/png;base64,iVBORw0KGgoAAAANSUhE...(ellipsis)

[Fig2]:data:image/png;base64,iVBORw0KGgoAAAANSUhE...(ellipsis)

Perfect solution, bid farewell to the drawing bed server!

I also package the program as an executable exe file. Just put the file in the directory where the markdown file is located.

Welcome to and star my gitee project markdown image to base64.

Keywords: Python Programmer

Added by Spekta on Sat, 19 Feb 2022 07:39:59 +0200