通过文件二进制信息判断图片类型(png,jpg,gif)

  1. package lab.sodino.img;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import javax.microedition.io.Connector;
  5. import javax.microedition.io.file.FileConnection;
  6. import javax.microedition.midlet.MIDlet;
  7. import javax.microedition.midlet.MIDletStateChangeException;
  8. /** @author sodino */
  9. public class ImgType extends MIDlet {
  10. public ImgType() {
  11. }
  12. protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
  13. }
  14. protected void pauseApp() {
  15. }
  16. protected void startApp() throws MIDletStateChangeException {
  17. String prefix = "file:///root1/";
  18. // testFile(prefix + "logo_cn.gif");
  19. // testFile(prefix + "04.jpg");
  20. testFile(prefix + "img.png");
  21. }
  22. public void testFile(String url) {
  23. try {
  24. int length = 10;
  25. FileConnection fc = (FileConnection) Connector.open(url);
  26. InputStream is = fc.openInputStream();
  27. byte[] data = new byte[length];
  28. is.read(data);
  29. String type = getType(data);
  30. System.out.println(url + " is " + type);
  31. is.close();
  32. fc.close();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. public String getType(byte[] data) {
  38. String type = null;
  39. // Png test:
  40. if (data[1] == 'P' && data[2] == 'N' && data[3] == 'G') {
  41. type = "PNG";
  42. return type;
  43. }
  44. // Gif test:
  45. if (data[0] == 'G' && data[1] == 'I' && data[2] == 'F') {
  46. type = "GIF";
  47. return type;
  48. }
  49. // JPG test:
  50. if (data[6] == 'J' && data[7] == 'F' && data[8] == 'I'
  51. && data[9] == 'F') {
  52. type = "JPG";
  53. return type;
  54. }
  55. return type;
  56. }
  57. }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值