图片的base64格式从内存中直接读入的python和java方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/abc15766228491/article/details/80500159

将图片的base64直接从内存中读取,不用存储在本地的方法的python和java实现

# 这个ls_f是base64编码
import cStringIO
imgdata = cStringIO.StringIO(base64.b64decode(ls_f))
true_image = Image.open(imgdata)
true_image.show()
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;

import java.io.*;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.awt.color.ColorSpace;
import java.awt.image.ColorConvertOp;

public static String GenerateImage(String imgStr) {   //对字节数组字符串进行Base64解码并生成图片
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }

            ByteArrayInputStream in = new ByteArrayInputStream(b);    //将b作为输入流;
            BufferedImage image = ImageIO.read(in);     //将in作为输入流,读取图片存入image中,而这里in可以为ByteArrayInputStream();
            ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
            ColorConvertOp op = new ColorConvertOp(cs, null);
            image = op.filter(image, null);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(image,"JPEG", out);

            byte[] data_byte = out.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
//            encoder.encode(data_byte);//返回Base64编码过的字节数组字符串
//            System.out.println(encoder.encode(data_byte));
            return encoder.encode(data_byte);
        } catch (Exception e) {
            return "";
        }
展开阅读全文

没有更多推荐了,返回首页