2017-09-25 97 views
-1

(注:我不能用它直接調整圖像的任何圖書館,我想知道調整的核心邏輯)如何減少在Java中的圖像尺寸

我有一個灰度圖像尺寸爲256 * 256。我想修改它並創建以下三個圖像a)尺寸爲128 * 128的圖像b)尺寸爲64 * 64的圖像c)尺寸爲32 * 32的圖像。

僞代碼

File fi = new File("E:\\input.raw"); 
byte[] fileContent = Files.readAllBytes(fi.toPath()); 

File fo= new File("E:\\output.raw"); 
FileOutputStream stream = new FileOutputStream(fo); 

int i=0; 
    for(;i<fileContent.length;i++){ 
    //dividing by 2 to create image with dimensions 128*128 
    fileContent[i]= (byte) ((fileContent[i])/2); 
    stream.write(fileContent[i]); 
    } 
    stream.close(); 

上面的代碼不work.It與256個* 256尺寸創建圖像。 由於某些原因,我不允許使用任何直接縮小尺寸的庫。我想知道如何將256 * 256圖像轉換爲128 * 128尺寸?

+0

「由於某些原因」。你的意思是這是某種面試或家庭作業問題。雖然家庭作業問題在這裏允許,但您需要首先展示您的工作。你基本上沒有寫任何東西。如果這是一個面試問題,你不適合這個地方。 – Kayaman

+0

@Kayaman我已經添加了我的工作中的代碼片斷。 – sar

+1

爲什麼你認爲劃分字節值會影響圖像的大小*?這沒有任何意義。 – Kayaman

回答

-1

希望這將有助於

/** 
* scale image 
* 
* @param sbi image to scale 
* @param imageType type of image 
* @param dWidth width of destination image 
* @param dHeight height of destination image 
* @param fWidth x-factor for transformation/scaling 
* @param fHeight y-factor for transformation/scaling 
* @return scaled image 
*/ 
public static BufferedImage scale(BufferedImage sbi, int imageType, int dWidth, int dHeight, double fWidth, double fHeight) { 
    BufferedImage dbi = null; 
    if(sbi != null) { 
     dbi = new BufferedImage(dWidth, dHeight, imageType); 
     Graphics2D g = dbi.createGraphics(); 
     AffineTransform at = AffineTransform.getScaleInstance(fWidth, fHeight); 
     g.drawRenderedImage(sbi, at); 
    } 
    return dbi; 
} 
+0

*「我不允許使用任何直接縮小尺寸的圖書館。」* – Filburt

+1

那麼他/她可以隨時在圖書館內查看,瞭解它是如何工作的,並自己寫下它 –

-1

使用ImageIOGraphics2D這是可以做到如下

BufferedImage originalImage = ImageIO.read(new File("c:\\image\\test.jpg")); 
int[] dims = {128, 64, 32}; 

for(int dim : dims) { 
    BufferedImage resizedImage = new BufferedImage(dim, dim, type); 
    Graphics2D g = resizedImage.createGraphics(); 
    g.drawImage(originalImage, 0, 0, dim, dim, null); 
    g.dispose(); 
    ImageIO.write(resizeImageJpg, "jpg", new File("c:\\image\\test_" + dim + "x" + dim + ".jpg")); 
} 
+0

*「我不允許使用任何直接縮小尺寸的庫「。* – Filburt

+0

[ImageIO](https://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html)和[Graphics2D](https:// docs.oracle.com/javase/7/docs/api/java/awt/Graphics2D.html)是不是外部的java內部庫 –

+0

請重新閱讀我的引用 - 它並不是指外部庫**,而是庫**直接減小尺寸**。很顯然,OP的任務只是爲了證明他可以解決問題而提出的一個頗有學問的要求。 OP甚至編輯他的文章來具體指出這一點。 – Filburt