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

来源:互联网 发布:柏拉图交友软件 编辑:程序博客网 时间:2024/05/29 20:00
  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 ImgTypeextends 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 0