跳至主要內容

Typora+MinIO+Java代码打造舒适写作环境

IT王小二约 1206 字

Typora+MinIO+Java代码打造舒适写作环境

作者:IT王小二

博客:https://itwxe.comopen in new window

前面小二介绍过使用Typora+PicGo+LskyPro打造舒适写作环境,那时候需要使用水印功能,但是小二在升级LskyPro2.x版本发现有很多不如人意的东西,遂弃用LskyPro使用MinIO结合代码实现自己需要的图床功能,也适合以后扩展功能。

安装MinIO

安装参考MinIO官网open in new window,或者参考小二的博客,搜索关键词 → Linux安装MinIO

安装完成之后使用域名映射好后台服务,小二使用nginx配置域名,配置参考如下。

    server {
        listen 443 ssl;
        server_name minio.itwxe.com;
        include /usr/local/nginx/conf/conf.d/common.conf;
        access_log logs/minioAccess.log;

        location / {
            proxy_pass http://127.0.0.1:9000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }

    server {
        listen 443 ssl;
        server_name minio-console.itwxe.com;
        include /usr/local/nginx/conf/conf.d/common.conf;
        access_log logs/minioAccess.log;

        location / {
            proxy_pass http://127.0.0.1:9020;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }

其中common.conf为域名通用配置。

        ssl_certificate /usr/local/nginx/ssl/fullchain.crt;
        ssl_certificate_key /usr/local/nginx/ssl/itwxe.com.key;
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout 30m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers HIGH:!aNULL:!MD5:!EXPORT56:!EXP;
        ssl_prefer_server_ciphers on;
        proxy_connect_timeout 500;
        proxy_send_timeout 500;
        proxy_read_timeout 500;
        client_max_body_size 100m;

配置好之后访问https://minio-console.itwxe.com即可访问后台。

同时为了存储桶图片所有人可以访问,需要将存储桶设置为公开。

设置存储桶为public

Java代码上传图片

Java代码为个人定制使用,仅供参考,整体项目目录结构。

项目目录结构

使用maven搭建Java项目,引入依赖,pom.xml如下。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itwxe</groupId>
    <artifactId>minio-typora</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- minio -->
        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.4.4</version>
        </dependency>
    </dependencies>


    <build>
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

增加配置类MinioConfig。

package com.itwxe.config;

/**
 * @author itwxe
 * @since 2022/9/29
 **/
public class MinioConfig {

    /**
     * 请求地址,需修改成自己的服务地址
     */
    public static final String ENDPOINT = "https://minio.itwxe.com";
    /**
     * 用户名,需修改为自己的用户名
     */
    public static final String ACCESS_KEY = "admin";
    /**
     * 秘钥,需修改为自己的密码
     */
    public static final String SECRET_KEY = "12345678";
    /**
     * 存储桶名称
     */
    public static final String BUCKET = "img";

}

增加主类进行图片上传。

package com.itwxe;

import com.itwxe.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author itwxe
 * @since 2022/9/29
 **/
public class MinioTyporaApplication {

    /**
     * 博客图片子路径
     */
    private static final String IMG_DIR = "blog";

    public static void main(String[] args) {
        try {
            // 使用MinIO服务器平台、其访问密钥和密钥创建minioClient。
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(MinioConfig.ENDPOINT)
                    .credentials(MinioConfig.ACCESS_KEY, MinioConfig.SECRET_KEY)
                    .build();
            // 博客文章唯一链接id
            String blogPermalink = args[0];
            if (blogPermalink.length() != 8) {
                System.out.println("文章唯一id未设置!");
                return;
            }
            // 循环上传图片
            for (int i = 1; i < args.length; i++) {
                String arg = args[i];
                // 生成自定义文件名, 规则为博客唯一链接id_时间戳+随机2位数
                String fileSuffix = arg.substring(arg.lastIndexOf("."));
                String fileName = String.format("%s_%s%02d%s", blogPermalink, LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli(), (int) (Math.random() * 100), fileSuffix);
                // 上传图片
                minioClient.uploadObject(UploadObjectArgs.builder()
                        .bucket(MinioConfig.BUCKET)
                        .object(String.format("/%s/%s", IMG_DIR, fileName))
                        .filename(arg)
                        .build());
                // 打印出来的字符会返回给typora
                System.out.println(String.format("%s/%s/%s/%s", MinioConfig.ENDPOINT, MinioConfig.BUCKET, IMG_DIR, fileName));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }

}

typora测试上传图片

为方便使用,使用mvn clean package打包成jar包,打开typora,偏好设置 -> 图像设置。

typora偏好设置

java -jar /Users/itwxe/minio-typora.jar fd52d52a

其中 /Users/itwxe/minio-typora.jar 为jar包路径,fd52d52a为小二个人定制的文章唯一id。

点击验证图片上传选项,正常返回测试路径,同时图片浏览器可以访问则代表成功。

增加图片大小压缩功能(可选)

使用OpenViewerFX来压缩图片大小,节省磁盘存储空间,加快响应速度,节省cdn流量。

首先需要在pom.xml中引入依赖jar包。

        <dependency>
            <groupId>org.jpedal</groupId>
            <artifactId>OpenViewerFX</artifactId>
            <version>6.6.14</version>
        </dependency>

MinioTyporaApplication中增加压缩图片的方法。

    /**
     * 压缩图片
     * @param sourcePath 原图片目标路径
     * @param outPath 目标图片路径
     */
    public static void openViewerFXPhotoCompress(String sourcePath, String outPath) {
        // 源文件
        File sourceFile = new File(sourcePath);
        // 目标输出文件,可与源文件一致,一致会覆盖
        File outFile = new File(outPath);
        try {
            PngCompressor.compress(sourceFile, outFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

main方法中合适的地方引用openViewerFXPhotoCompress()方法,上传图片之前进行压缩。

            // 循环上传图片
            for (int i = 1; i < args.length; i++) {
                String arg = args[i];
                // 压缩图片
                openViewerFXPhotoCompress(arg, arg);
                // 生成自定义文件名, 规则为博客唯一链接id_时间戳+随机2位数
                String fileSuffix = arg.substring(arg.lastIndexOf("."));
                String fileName = String.format("%s_%s%02d%s", blogPermalink, LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli(), (int) (Math.random() * 100), fileSuffix);
                // 上传图片
                minioClient.uploadObject(UploadObjectArgs.builder()
                        .bucket(MinioConfig.BUCKET)
                        .object(String.format("/%s/%s", IMG_DIR, fileName))
                        .filename(arg)
                        .build());
                // 打印出来的字符会返回给typora
                System.out.println(String.format("%s/%s/%s/%s", MinioConfig.ENDPOINT, MinioConfig.BUCKET, IMG_DIR, fileName));
            }