문제

내 강사가 나 에게이 코드를 보냈는데,이 코드는 진행중인 프로젝트의 필수 부분으로 여겨졌다. 문제가 작동하지 않습니다.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.Kernel;
import java.awt.image.ConvolveOp;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import javax.swing.*;


public class ImageUtil {

    public static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException{

        if(quality <0||quality>1){
            throw new IllegalArgumentException ("quality has to be between 0 and 1");

        }

        ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
        Image i = ii.getImage();
        Image resizedImage = null;

        int iWidth = i.getWidth (null);
        int iHeight = i.getHeight(null);

        if (iWidth > iHeight){
            resizedImage = i.getScaledInstance(newWidth,(newWidth*iHeight)/iWidth, Image.SCALE_SMOOTH);
        } else {
            resizedImage = i.getScaledInstance((newWidth*iWidth)/iHeight,newWidth, Image.SCALE_SMOOTH);
        }

        Image temp = new ImageIcon (resizedImage).getImage();

        BufferedImage bufferedImage = new BufferedImage (temp.getWidth(null), temp.getHeight(null),
                                                         BufferedImage.TYPE_INT_RGB);

        // copy to a buffered image
        Graphics g = bufferedImage.createGraphics();

        g.setColor(Color.white);
        g.fillRect(0,0,temp.getWidth(null), temp.getHeight(null)); // causea el error de ejecución?
        g.drawImage(temp,0,0,null);
        g.dispose();

        float softenFactor = 0.05f;
        float [] softenArray = {0, softenFactor,0, softenFactor, 1-(softenFactor*4), softenFactor,0, softenFactor,0};
        Kernel kernel = new Kernel (3,3,softenArray);
        ConvolveOp cOp = new ConvolveOp (kernel, ConvolveOp.EDGE_NO_OP,null);
        bufferedImage = cOp.filter (bufferedImage,null);

        FileOutputStream out = new FileOutputStream(resizedFile);

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);

        param.setQuality(quality,true);

        encoder.setJPEGEncodeParam(param);
        encoder.encode(bufferedImage);



    }

    public static void main(String args[]) throws IOException {
       File originalImage= new File ("/images/goya.jpg");
       resize(originalImage,new File("/images/goyanuevotamanio.jpg"),350, 0.2f);
       resize(originalImage, new File("/images/goyanuevotamanio.jpg"), 350, 1f);

    }

}

그는 코드가 높이와 너비를 크기를 조정할 수 있지만 그의 크기 조정 방법을 모두 크기를 수 있어야한다고 말했다.

public static void resize(File originalFile, File resizedFile, int newWidth, float quality)

부족 newHeight 매개 변수.

던져진 runtimeexception은 다음과 같이 말합니다.

Exception in thread "main" java.lang.IllegalArgumentException: **Width (-1) and height (-1) cannot be <= 0**
        at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:999)
        at java.awt.image.BufferedImage.<init>(BufferedImage.java:312)
        at ImageUtil.resize(ImageUtil.java:38)
        at ImageUtil.main(ImageUtil.java:72)
Java Result: 1

이것을 어떻게 변경할 수 있습니까?

도움이 되었습니까?

해결책

문제가 무엇인지 확인하기 위해 코드를 분석하지 않으면 이미지의 종횡비를 유지하려는 의도가 새로운 높이 매개 변수가 필요하지 않다고 말할 수 있습니다. 항상 너비의 고정 비율입니다.

업데이트:

나는 내 자신의 테스트 이미지에 대해 코드를 실행하며 실제로 예상대로 작동합니다. 프로그램이 지정한 소스 이미지를 찾을 수 없을 때 얻을 수있는 오류가 발생할 가능성이 높습니다. 존재하지 않는 소스 이미지를 지정할 때 동일한 오류가 발생합니다.

소스 이미지에 절대 경로 (드라이브 문자 포함)를 사용해보십시오.

업데이트 2

줄 뒤에 다음 코드를 추가하십시오 ..

ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());

if(ii.getImageLoadStatus() == MediaTracker.COMPLETE)
{
    System.out.print("Load image ok\n");
}
else
{
    System.out.print("Load image failed\n");
}

이것은 프로그램이 소스 이미지를로드하지 못하는지 알려줍니다.

다른 팁

크기를 조정하기 위해 부드럽게 적용 해야하는 이유 Kernal -1 -2 -1 -2 12+Q -2 -1 -2 -1 팁 Q가 28 일 수 있고 DrawImage의 크기 조정 버전을 적용하지 않습니다.

(Q = 36은 날카로운 경우 F = 0.05에 해당합니다)

스택 추적으로 판단하면 예외 가이 줄에 의해 발생됩니다.

BufferedImage bufferedImage = new BufferedImage (temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

나는 이것이 아마도 때문이라고 생각할 것이다 temp.getWidth 그리고 temp.getHeight 이미지가로드가 완료되지 않았기 때문에 -1을 반환합니다.

웹에서 사용할 수있는 Java의 이미지 작업을위한 자습서와 예제가 있습니다. 하나의 샘플이 여기에 있습니다 http://snippets.dzone.com/posts/show/92. 사용 사용 코드를 찾으십시오 ImageObserver.

당신은 프로그램에 0과 1 사이의 시작 매개 변수를 제공해야합니다. 나는 그것을했고 완벽하게 작동합니다.

이것에 적응하십시오 :

private void ResizeImage(Image img, double maxWidth, double maxHeight)
{
    double srcWidth = img.Source.Width;
    double srcHeight = img.Source.Height;

    double resizeWidth = srcWidth;
    double resizeHeight = srcHeight;

    double aspect = resizeWidth / resizeHeight;

    if (resizeWidth > maxWidth)
    {
        resizeWidth = maxWidth;
        resizeHeight = resizeWidth / aspect;
    }
    if (resizeHeight > maxHeight)
    {
        aspect = resizeWidth / resizeHeight;
        resizeHeight = maxHeight;
        resizeWidth = resizeHeight * aspect;
    }

    img.Width = resizeWidth;
    img.Height = resizeHeight;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top