2013-04-10 70 views
10

Tôi đã xoay vòng hình ảnh 180 degrees nhưng muốn xoay hình 90 degreesclockwise ai đó có thể chỉnh sửa mã của tôi để giải thích điều này. Cảm ơn.xoay hình ảnh 90 độ trong java

private void rotateClockwise() 
    { 
     if(currentImage != null){ 
      int width = currentImage.getWidth(); 
      int height = currentImage.getHeight(); 
      OFImage newImage = new OFImage(width, height); 
      for(int y = 0; y < height; y++) { 
       for(int x = 0; x < width; x++) { 
        newImage.setPixel(x, height-y-1, currentImage.getPixel(x, y)); 
       } 
     } 
      currentImage = newImage; 
      imagePanel.setImage(currentImage); 
      frame.pack(); 
    } 
    } 
+1

Hãy thử suy nghĩ điều gì sẽ xảy ra với mỗi phần tư hình ảnh khi bạn xoay hình ảnh. Tôi nghĩ đó nên là một cách tiếp cận tốt. Giải quyết từng quý một. –

+3

[ví dụ] (http://forum.codecall.net/topic/69182-java-image-rotation/) –

+0

Cảm ơn ví dụ Vignesh Vino. Tôi quản lý để làm cho nó làm việc nhiều đánh giá cao. –

Trả lời

14

Sử dụng phương pháp này.

/** 
* Rotates an image. Actually rotates a new copy of the image. 
* 
* @param img The image to be rotated 
* @param angle The angle in degrees 
* @return The rotated image 
*/ 
public static Image rotate(Image img, double angle) 
{ 
    double sin = Math.abs(Math.sin(Math.toRadians(angle))), 
      cos = Math.abs(Math.cos(Math.toRadians(angle))); 

    int w = img.getWidth(null), h = img.getHeight(null); 

    int neww = (int) Math.floor(w*cos + h*sin), 
     newh = (int) Math.floor(h*cos + w*sin); 

    BufferedImage bimg = toBufferedImage(getEmptyImage(neww, newh)); 
    Graphics2D g = bimg.createGraphics(); 

    g.translate((neww-w)/2, (newh-h)/2); 
    g.rotate(Math.toRadians(angle), w/2, h/2); 
    g.drawRenderedImage(toBufferedImage(img), null); 
    g.dispose(); 

    return toImage(bimg); 
} 

lấy từ lớp ImageTool của tôi.

Hy vọng điều đó sẽ hữu ích.

+0

tại sao bạn sao chép hình ảnh, nó không hoàn thành bằng cách áp dụng biến đổi 90 độ affine trong khi vẽ? vui lòng làm rõ. – Mihir

+0

@Mihir Đó là yêu cầu đối với trò chơi của tôi. Lớp này là từ công cụ trò chơi của tôi vì vậy tôi đã sử dụng nó. Bạn có thể sử dụng bất cứ điều gì bạn thích. –

+0

cảm ơn bạn đã làm rõ – Mihir

Các vấn đề liên quan