gusucode.com > 基于matlab的JPEG彩色图像编码解码源码程序 > 基于matlab的JPEG彩色图像编码解码源码程序/code/main.m
%% 清空环境 close all; clc; clear; %% 图像压缩 filePath='2.bmp';%被压缩的图像的途径 quantizationFactor=0.5;%该变量为量化因子,最小为0.01,最大为255,建议在0.5和3之间,越小质量越好文件越大 I=imread(filePath);%读bmp彩色图像 FileCode=encode(I,quantizationFactor);%压缩图像 %保存文件 savePath='save.myjpeg';%文件保存路径 fileID = fopen(savePath, 'w'); for i=1:8:length(FileCode)-8 fwrite(fileID,bin2dec(FileCode(i:i+7)),'uint8'); end i=i+8; if i<=length(FileCode) %剩余位数不足一个字节,补零 lastBitsCount=length(FileCode)-i+1; lastByte=['0' '0' '0' '0' '0' '0' '0' '0' ]; lastByte(1:lastBitsCount)=FileCode(i:length(FileCode)); fwrite(fileID,bin2dec(lastByte),'uint8'); end fclose(fileID); %计算压缩比 listing=dir(filePath); originalSize=listing.bytes; listing=dir(savePath); currentSize=listing.bytes; disp(['压缩比率为' num2str(originalSize/currentSize)]); %% 读取文件并解压缩图像 fileID2 = fopen(savePath, 'r'); Bytes=fread(fileID2,inf,'uint8'); fclose(fileID2); Codes=dec2bin(Bytes,8);%传化为字符串,方便解码时取一位操作 FileCode2=reshape(Codes',1,length(Codes)*8);%获得字符代表码流,将每组字节码,合并成一个字符串 I2=decode(FileCode2);%解压缩 %% 测试对比 [m n ~]=size(I2); disp(['比特率为' num2str(currentSize*8/(m*n))]);%输出比特率 disp(['信噪比为' num2str(PSNR(I,I2))]);%输出信噪比 %原图像与压缩图像对比imwrite figure('Name','原图像','NumberTitle','off'),imshow(I); figure('Name','压缩图像','NumberTitle','off'),imshow(I2);