2011-05-01 4 views
2

사진이있는 폴더를 선택해야하는 곳에서 Java를 사용하여 해당 이미지의 축소판보기를 표시해야하는 응용 프로그램이 있습니다. 축소판 형식으로 이미지를 표현하는 방법에 대한 아이디어가 없습니다.Java를 사용하여 이미지 축소판보기 만들기

코드 예제, 이론 또는 링크와 같은 모든 리소스가 도움이 될 것입니다.

고맙습니다.

+0

어떻게 축소판의 크기를 조정 하시겠습니까? 일부 이미지는 높음보다 너비가 더 클 수 있습니다. y 방향에서와 같이 x에서 같은 크기로 조정해야합니까? – extraneon

답변

1

나는 내 프로젝트에서이 코드를 사용하고 있습니다. 나는 얼마 전에 인터넷에서 발견 (사람이 인식하면 그것은 나를 그래서 그것을 참조 할 수 있습니다 알려 주시기 바랍니다 어디하지만 확실하지) :

private static byte[] createThumbnail(byte[] bytes) 
{ 
    try 
    { 
     double scale; 
     int sizeDifference, originalImageLargestDim; 
     Image inImage = ImageIO.read(new ByteArrayInputStream(bytes)); 

     //find biggest dimension   
     if(inImage.getWidth(null) > inImage.getHeight(null)) 
     { 
      scale = (double)LARGEST_DIMENSION/(double)inImage.getWidth(null); 
      sizeDifference = inImage.getWidth(null) - LARGEST_DIMENSION; 
      originalImageLargestDim = inImage.getWidth(null); 
     } 
     else 
     { 
      scale = (double)LARGEST_DIMENSION/(double)inImage.getHeight(null); 
      sizeDifference = inImage.getHeight(null) - LARGEST_DIMENSION; 
      originalImageLargestDim = inImage.getHeight(null); 
     } 
     //create an image buffer to draw to 
     BufferedImage outImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); //arbitrary init so code compiles 
     Graphics2D g2d; 
     AffineTransform tx; 
     if(scale < 1.0d) //only scale if desired size is smaller than original 
     { 
      int numSteps = sizeDifference/100; 
      int stepSize = sizeDifference/numSteps; 
      int stepWeight = stepSize/2; 
      int heavierStepSize = stepSize + stepWeight; 
      int lighterStepSize = stepSize - stepWeight; 
      int currentStepSize, centerStep; 
      double scaledW = inImage.getWidth(null); 
      double scaledH = inImage.getHeight(null); 
      if(numSteps % 2 == 1) //if there's an odd number of steps 
       centerStep = (int)Math.ceil((double)numSteps/2d); //find the center step 
      else 
       centerStep = -1; //set it to -1 so it's ignored later 
      Integer intermediateSize = originalImageLargestDim, previousIntermediateSize = originalImageLargestDim; 
      for(Integer i=0; i<numSteps; i++) 
      { 
       if(i+1 != centerStep) //if this isn't the center step 
       { 
        if(i == numSteps-1) //if this is the last step 
        { 
         //fix the stepsize to account for decimal place errors previously 
         currentStepSize = previousIntermediateSize - LARGEST_DIMENSION; 
        } 
        else 
        { 
         if(numSteps - i > numSteps/2) //if we're in the first half of the reductions 
          currentStepSize = heavierStepSize; 
         else 
          currentStepSize = lighterStepSize; 
        } 
       } 
       else //center step, use natural step size 
       {       
        currentStepSize = stepSize; 
       } 
       intermediateSize = previousIntermediateSize - currentStepSize; 
       scale = (double)intermediateSize/(double)previousIntermediateSize; 
       scaledW = (int)scaledW*scale; 
       scaledH = (int)scaledH*scale; 
       outImage = new BufferedImage((int)scaledW, (int)scaledH, BufferedImage.TYPE_INT_RGB); 
       g2d = outImage.createGraphics(); 
       g2d.setBackground(Color.WHITE); 
       g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight()); 
       g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); 
       tx = new AffineTransform(); 
       tx.scale(scale, scale); 
       g2d.drawImage(inImage, tx, null); 
       g2d.dispose(); 
       inImage = new ImageIcon(outImage).getImage(); 
       previousIntermediateSize = intermediateSize; 
      }     
     } 
     else 
     { 
      //just copy the original 
      outImage = new BufferedImage(inImage.getWidth(null), inImage.getHeight(null), BufferedImage.TYPE_INT_RGB); 
      g2d = outImage.createGraphics(); 
      g2d.setBackground(Color.WHITE); 
      g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight()); 
      tx = new AffineTransform(); 
      tx.setToIdentity(); //use identity matrix so image is copied exactly 
      g2d.drawImage(inImage, tx, null); 
      g2d.dispose(); 
     } 
     //JPEG-encode the image and write to file. 
     ByteArrayOutputStream os = new ByteArrayOutputStream(); 
     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os); 
     encoder.encode(outImage); 
     return os.toByteArray(); 
    } 
    catch(Exception e) 
    { 
     throw new RuntimeException(e); 
    } 
} 
1

다음 코드는 지역에 전체 이미지를 확장 할 수 있습니다. 코드를 복사하여 붙여 넣기하여 실행할 수 있습니다.

흥미로운 전화는 g2d.drawImage(img, 0, 0, thumb.getWidth() - 1, thumb.getHeight() - 1, 0, 0, img.getWidth() - 1, img.getHeight() - 1, null);입니다.이 이미지는 축소판에 이미지를 복사하고 크기가 맞춰집니다.

가로 세로 비율을 유지하기 위해 다른 크기 조정을 원하면 g2d에서 scale()을 사용하거나 다른 원본 좌표를 선택할 수 있습니다.

import java.awt.Graphics2D; 
import java.awt.image.BufferedImage; 
import java.io.File; 

import javax.imageio.ImageIO; 

public class ThumbnailFactory { 

    public ThumbnailFactory() { 
    } 

    public void run(String folder) { 
     File dir = new File(folder); 
     for (File file : dir.listFiles()) { 
      createThumbnail(file); 
     } 
    } 

    private void createThumbnail(File file) { 
     try { 
      // BufferedImage is the best (Toolkit images are less flexible) 
      BufferedImage img = ImageIO.read(file); 
      BufferedImage thumb = createEmptyThumbnail(); 

      // BufferedImage has a Graphics2D 
      Graphics2D g2d = (Graphics2D) thumb.getGraphics(); 
      g2d.drawImage(img, 0, 0, 
          thumb.getWidth() - 1, 
          thumb.getHeight() - 1, 
          0, 0, 
          img.getWidth() - 1, 
          img.getHeight() - 1, 
          null); 
      g2d.dispose(); 
      ImageIO.write(thumb, "PNG", createOutputFile(file)); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    private File createOutputFile(File inputFile) { 
     // You'll want something better than this... 
     return new File(inputFile.getAbsolutePath() 
         + ".thumb.png"); 
    } 

    private BufferedImage createEmptyThumbnail() { 
     return new BufferedImage(100, 200, 
           BufferedImage.TYPE_INT_RGB); 
    } 

    public static void main(String[] args) { 
     ThumbnailFactory fac = new ThumbnailFactory(); 
     fac.run("c:\\images"); 
    } 
} 
관련 문제