图片转Base64上传至服务器

本文介绍如何将图片转换为Base64编码,并提供具体的代码实现。包括保存图片、图片转Base64的方法及在HTML/CSS中的应用,还涉及多张图片的上传处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

1.将图片转换为Base64编码,可以让你很方便地在没有上传文件的条件下将图片插入其它的网页、编辑器中。 这对于一些小的图片是极为方便的,因为你不需要再去寻找一个保存图片的地方。

2.假定生成的代码为"data:image/jpeg;base64, .....",那么你只需要全部复制,然后在插入图片的时候,地址填写这段代码即可。

3.CSS中使用:background-image: url("https://img-blog.csdnimg.cn/2022010621142225147.png");

4.HTML中使用:<img src="https://img-blog.csdnimg.cn/2022010621142225147.png" />

 

图片转Base64具体代码实现

 

1.保存图片

 

  /**
     * 指定保存路径
     * @param bmp
     */
    public void saveImageToGallery(Bitmap bmp) {
        imgHead.setImageBitmap(bmp);
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "ymf");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".png";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filePath = Environment.getExternalStorageDirectory() + "/ymf/" + fileName;
        String imgPath = encodeFileToBase64Binary(filePath);
        postDataUploadImg("data:image/png;base64," + imgPath);
    }

 

2.图片转Bae64encodeFileToBase64Binary(filePath)

 


    private static String encodeFileToBase64Binary(String filePath) {
        byte[] bytes = FileIOUtil.readFile2BytesByStream(filePath);
        byte[] encoded = Base64.encode(bytes, Base64.DEFAULT);
        return new String(encoded);
    }

 

3.转换工具类

 

package com.artmofang.utils;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


/**
 * @author yang
 */
public class FileIOUtil {

    private static int sBufferSize = 8192;

    /**
     * 读取文件到字节数组中
     *
     * @param filePath 文件路径
     * @return 字符数组
     */
    public static byte[] readFile2BytesByStream(final String filePath) {
        return readFile2BytesByStream(getFileByPath(filePath));
    }

    public static byte[] readFile2BytesByStream(final File file) {
        if (!isFileExists(file)) {
            return null;
        }
        FileInputStream fis = null;
        ByteArrayOutputStream os = null;
        try {
            fis = new FileInputStream(file);
            os = new ByteArrayOutputStream();
            byte[] b = new byte[sBufferSize];
            int len;
            while ((len = fis.read(b, 0, sBufferSize)) != -1) {
                os.write(b, 0, len);
            }
            return os.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            closeIO(fis, os);
        }
    }

    public static void closeIO(final Closeable... closeables) {
        if (closeables == null) {
            return;
        }
        for (Closeable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static File getFileByPath(final String filePath) {
        return isSpace(filePath) ? null : new File(filePath);
    }

    private static boolean isSpace(final String s) {
        if (s == null) {
            return true;
        }
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    private static boolean isFileExists(final File file) {
        return file != null && file.exists();
    }
}

 

4.上传数据

 

//上传头像
 postDataUploadImg("data:image/png;base64," + imgPath);


  /**
     * 上传头像
     *
     * @param s
     */

    private void postDataUploadImg(String s) {
        HashMap<String, String> map = new HashMap<>();
        map.put("img", s);
        ArtMoFangManager.getInstance().upLoadHeadImgBean(map, getSubscriber(Constants.UPLOADHEADIMG));
    }

 

上面的代码我们实现了上传一张图片,那么多张图片如何实现上传呢?很明显经过Base64加密过的图片是一串字符串,我们可以把这些字符串拼接起来,之间可以用特殊符号隔开  比如:#符号,这个需要前段开发人员自己和后台确认,字符串之间隔开的方式。在这里我是以 符号  “#”隔开字符串的。代码实现如下:

 

  private void postSubmitData() {
        HashMap<String, String> map = new HashMap<>();
        for (String imgPath : pathList) {

            if (pathList.size() == 1) {
                Images = encodeFileToBase64Binary(imgPath);
                tempImages = "data:image/png;base64," + Images + "#";
            } else if (pathList.size() == 2) {
                Images = encodeFileToBase64Binary(imgPath);
                tempImages = "data:image/png;base64," + Images + "#";
            } else {
                Images = encodeFileToBase64Binary(imgPath);
                tempImages = "data:image/png;base64," + Images + "#" + tempImages;
            }
        }
       
        map.put("title", mTitle);
        map.put("content", imageshtml);
        map.put("cat_id", cat_id);
        map.put("art_type", "2");
        map.put("images", "" + tempImages);
        ArtMoFangManager.getInstance().questionContriubtionSubmit(map, getSubscriber(Constants.QUESTIONCONTRIBUTIONS));
    }

注:

tempImages是中间变量,用来拼接最终字符串的。
Images是Base64处理后的图片。

注意的一点:Base64处理图片,一定要拼接上data:image/png;base64, 这个字符串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值