使用gif4j库写一个Java的GUI小程序压缩动态gif图片

本文介绍了如何使用Java GUI和Gif4J库创建一个小程序,该程序通过减少帧数来压缩动态gif图片,以应对微信等平台的图片大小限制。作者分享了程序的目录结构,并提供了源码的GitHub链接。
摘要由CSDN通过智能技术生成

    由于微信发图片有大小限制,用Photoshop转换倒是可以做到把图片缩小,但操作起来比较麻烦,所以自己动手用Java写了个小程序,以减少帧数的方式把动态图片压缩,这方法适用于帧数比较多的gif图片。

    在写这个程序之前百度过能完成编辑图片的几个比较有名的Java库,最终使用了Gif4J,感觉这个比较简单,下面是目录结构


    因为是即兴之作,所以也命名方式不够严谨,请见谅,源码可以在本人的github上面下载https://github.com/yesqwang/GitEditor.git

    UI及程序入口代码 MainUI.java

package gif.ui;

import gif.function.Edit;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class MainUI extends JFrame implements ActionListener{

	private static final long serialVersionUID = 1L;
	JTextField path;
	JLabel label_path;
	JButton edit;
	JTextArea area;
	JScrollPane pane;
	
	public MainUI() {
		super("GIF图片压缩器");
		init();
	}

	/**
	 * 初始化界面
	 */
	private void init() {
		
		path = new JTextField(20);
		label_path = new JLabel("图片所在文件夹路径࿱
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用LZW方法压缩bmp图片生成gif图片的Python程序: ```python import struct from PIL import Image def lzw_compress(data): dictionary = {} for i in range(256): dictionary[chr(i)] = i result = [] w = "" for c in data: wc = w + c if wc in dictionary: w = wc else: result.append(dictionary[w]) dictionary[wc] = len(dictionary) w = c if w: result.append(dictionary[w]) return result def compress_file(input_file, output_file): with open(input_file, "rb") as f: data = f.read() compressed_data = lzw_compress(data) with open(output_file, "wb") as f: for i in range(0, len(compressed_data), 2): if i + 1 < len(compressed_data): f.write(struct.pack("<H", (compressed_data[i] << 8) | compressed_data[i+1])) else: f.write(struct.pack("<H", compressed_data[i] << 8)) def bmp_to_gif(input_file, output_file): im = Image.open(input_file) im.save("temp.bmp") compress_file("temp.bmp", "temp.lzw") with open("temp.lzw", "rb") as f: data = f.read() im_gif = Image.new("P", im.size) im_gif.putpalette(im.getpalette()) im_gif.putdata(data) im_gif.save(output_file, format="GIF") bmp_to_gif("input.bmp", "output.gif") ``` 此程序将输入的bmp图片进行LZW压缩并生成gif图片。其中,`lzw_compress`函数和`compress_file`函数与上一个程序相同。`bmp_to_gif`函数用于将输入的bmp图片转换为gif图片,具体实现过程为:先将bmp图片保存为临时文件`temp.bmp`,然后对该文件进行LZW压缩,并将压缩后的数据用`putdata`方法gif图片中。最后,将生成的gif图片保存到输出文件中。这里使用了Python的第三方Pillow,用于处理图像。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值