使用C、python实现 通过图片base64数据计算图片大小

C代码示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
long estimate_file_size(const char* base64_data) {
    long base64_length = strlen(base64_data);
    long num_padding_chars = 0;
    
    // 计算Base64数据中的填充字符数
    if (base64_data[base64_length - 1] == '=') {
        num_padding_chars++;
        if (base64_data[base64_length - 2] == '=') {
            num_padding_chars++;
        }
    }
    
    // 实际文件大小是Base64块的3/4,每四个Base64字符表示三个字节
    long estimated_file_size = num_base64_blocks * 3 / 4 - num_padding_chars;
    
    return estimated_file_size;
}
 
int main() {
    const char* base64_data = "VGhpcyBpcyBhIHRlc3Q="; // 示例Base64编码数据
    long size = estimate_file_size(base64_data);
    printf("Estimated file size: %ld bytes\n", size);
    return 0;
}

Python代码示例

import base64
import io

def calculate_image_size(base64_data):
    # 解码base64数据
    image_data = base64.b64decode(base64_data)
    
    # 计算二进制数据的长度
    data_length = len(image_data)
    
    # 将长度转换为文件大小(例如,以KB、MB或GB为单位)
    file_size = data_length / 1024  # KB
    return file_size

# 示例
base64_data = "iVBORw0KGg..."
file_size = calculate_image_size(base64_data)
print("文件大小:", file_size, "KB")
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值