質問

講師からこのコードが送られてきました。これは進行中のプロジェクトに不可欠な部分であるはずです。問題は、それは機能しないということです。

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");
}

これにより、プログラムがソース イメージのロードに失敗しているかどうかがわかります。

他のヒント

あなたはそれがカーネル-1 -2 -1研ぐする必要がサイズを変更するために柔らかく適用なぜ-2 12 + Q -2 -1 -2 -1 tipical qは28可能性があり、あなたがのリサイズ版をapplyngされていませんdrawImage

(Q = 36のオーナーF =シャープ0.05に相当します)

この行によってスローされる例外をトレーススタックによって判断ます:

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

私はtemp.getWidthtemp.getHeightが戻ってきているので、-1画像の読み込みが完了していないので、これはおそらくあると思うだろう。

ウェブ上で利用できるJavaで画像を操作するためのチュートリアルと例があります。 1つのサンプルはこちら 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;
}
scroll top