如何将图像压缩到低于1kb?有可能吗?
这是我在线使用一些参考资料创建的代码。
它将图像文件大小减小到1.2 kb,但图像质量大大降低
压缩图像的功能
private void SaveAndCompressImage()
{
if (OriginalImage == null) return;
long compression = long.Parse(20);
string file_name = Directory.GetCurrentDirectory() +
"filename.jpg";
OriginalImage = new Bitmap(OriginalImage, new Size(100, 100));
SaveJpg(OriginalImage, file_name, compression);
// Display the result without locking the file.
UserPic.Image = LoadBitmapUnlocked(file_name);
Image PictureBoxPic = UserPic.Image;
Image pic = new Bitmap(PictureBoxPic, new Size(100, 100));
// Used For applying grayscale reduces image file size
Image gray_scale_image = ToolStripRenderer.CreateDisabledImage(pic);
Image output = gray_scale_image;
output.Save( file, ImageFormat.Jpeg);
// Used to Convert Image to Base64
ConvertImageToBase64 = Functions.CreateBase64Image(file);
}
用于保存具有压缩级别的图像
// Save the file with a specific compression level.
private void SaveJpg(Image image, string file_name, long compression)
{
try
{
EncoderParameters encoder_params = new EncoderParameters(1);
encoder_params.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.Quality, compression);
ImageCodecInfo image_codec_info = GetEncoderInfo("image/jpeg");
File.Delete(file_name);
image.Save(file_name, image_codec_info, encoder_params);
}
catch (Exception ex)
{
}
}
加载位图而不锁定它。
private Bitmap LoadBitmapUnlocked(string file_name)
{
using (Bitmap bm = new Bitmap(file_name))
{
return new Bitmap(bm);
}
}
返回此mime类型的ImageCodecInfo对象
private ImageCodecInfo GetEncoderInfo(string mime_type)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int i = 0; i <= encoders.Length; i++)
{
if (encoders[i].MimeType == mime_type) return encoders[i];
}
return null;
}