使用Java等比例縮放映像

來源:互聯網
上載者:User
本文為原創,如需轉載,請註明作者和出處,謝謝!









   
縮放映像的基本原理是建立一個目標大小的畫布,然後讀取源映像,並將該映像繪製這個畫布上。為了使程式通用,源映像和縮放後的靶心圖表像應用分別使用
InputStream和OutputStream來表示,代碼如下:

    
public
 
static
 
void
 scaleImage(InputStream imgInputStream,
            OutputStream imgOutputStream, 
int
 scale)
    {
        
try

        {

            Image src 
=
 javax.imageio.ImageIO.read(imgInputStream);
            
int
 width 
=
 (
int
) (src.getWidth(
null

*
 scale 
/
 
100.0
);
            
int
 height 
=
 (
int
) (src.getHeight(
null

*
 scale 
/
 
100.0
);
            BufferedImage bufferedImage 
=
 
new
 BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);

             bufferedImage.getGraphics().drawImage(
                    src.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    
0

0

null
);
            JPEGImageEncoder encoder 
=
 JPEGCodec
                    .createJPEGEncoder(imgOutputStream);
            encoder.encode( bufferedImage);

        }
        
catch
 (IOException e)
        {
            e.printStackTrace();
        }
    }


    其中scale參數表示縮放比例,1至100,當然,也可以大於100,那就是放大映像了。但要注意,放得太大會失真的。
    當然,也可以重構scaleImage方法,使其可以接收影像檔名,代碼如下:

    
public
 
static
 
void
 scaleImage(String imgSrc, String imgDist, 
int
 scale)
    {
        
try

        {
            File file 
=
 
new
 File(imgSrc);
            
if
 (
!
file.exists())
            {
                
return
;
            }
            InputStream is 
=
 
new
 FileInputStream(file);
            OutputStream os 
=
 
new
 FileOutputStream(imgDist);
            scaleImage(is, os, scale);
            is.close();
            os.close();
        }
        
catch
 (Exception e)
        {



        }
    }


    下面的代碼按15%縮放

scaleImage(
"
E://pictures//test.jpg
"

"
e://test1.jpg
"

15
);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.