道非道 非常道

          勤思、謹(jǐn)言、慎行、厚積、薄發(fā)

          統(tǒng)計(jì)

          web

          天圓

          經(jīng)濟(jì) 政治 軍事

          鍵康

          Java判斷圖片文件的類型

          轉(zhuǎn)自網(wǎng)絡(luò)
              判斷文件的類型,而不是判斷文件的后綴名



          import java.io.*;
          import javax.imageio.*;
          import java.util.*;
          import javax.imageio.stream.*;

          public class Test {
              
          public static void main(String[] args) {
                  File f 
          = new File("c://test//3.jpg");
                  
          if (f.exists()) {
                      System.out.println(getFormatInFile(f));
                  }
              }

              
          // Returns the format of the image in the file 'f'.
              
          // Returns null if the format is not known.
              public static String getFormatInFile(File f) {
                  
          return getFormatName(f);
              }

              
          // Returns the format name of the image in the object 'o'.
              
          // Returns null if the format is not known.
              private static String getFormatName(Object o) {
                  
          try {
                      
          // Create an image input stream on the image
                      ImageInputStream iis = ImageIO.createImageInputStream(o);

                      
          // Find all image readers that recognize the image format
                      Iterator iter = ImageIO.getImageReaders(iis);
                      
          if (!iter.hasNext()) {
                          
          // No readers found
                          return null;
                      }

                      
          // Use the first reader
                      ImageReader reader = (ImageReader) iter.next();

                      
          // Close stream
                      iis.close();

                      
          // Return the format name
                      return reader.getFormatName();
                  } 
          catch (IOException e) {
                      
          //
                  }

                  
          // The image could not be read
                  return null;
              }
          }


          posted on 2010-03-17 15:04 星期五 閱讀(977) 評(píng)論(0)  編輯  收藏 所屬分類: J2SE


          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 珠海市| 德保县| 淮安市| 上林县| 揭阳市| 滨州市| 稻城县| 巴林右旗| 涪陵区| 乌拉特前旗| 措勤县| 堆龙德庆县| 海门市| 扬州市| 东乌珠穆沁旗| 钟山县| 河南省| 信丰县| 偏关县| 永济市| 石柱| 肇庆市| 建湖县| 剑川县| 商丘市| 东丽区| 开阳县| 灌南县| 普兰县| 凤城市| 安多县| 搜索| 如皋市| 崇左市| 三江| 郎溪县| 米泉市| 西青区| 台南县| 凤阳县| 阜宁县|