Java映像漸層

來源:互聯網
上載者:User

映像漸層我們大體想一下思路無非是這樣:將映像所有的像素點的RBG,每個點就減去相同的量,而且這個量是個漸層的量。是的,就是這樣,我們的程式也是這個思路,不過就是沒有單純的“想”這麼簡單了。我這裡只編寫了縱向漸層,還沒有寫其他複雜的漸層,以後慢慢研究吧。先看效果: 

原始圖片: 


映像變暗漸層: 


映像變暗漸層: 


映像變亮漸層: 


映像變亮漸層: 


我們以映像漸層暗舉例,漸層亮同樣的道理,無非是一個減,一個加。 
1.我們要先拿到圖片,這個不贅述了,就是獲得映像的BufferedImage。 
2.獲得映像的寬度,高度,像素值,並建立一個儲存映像像素資訊DirectColorModel類dem。然後我們從dem中每一個像素值。我們給每一個像素都減去一個相同的像素值。並且伴隨著圖片的高度不同,每個像素點減去的值也是一個漸層的值。這裡需要說明一下的是float beginPart,beginPart是漸層開始的位置,預設為1,就是從映像中間開始,beginPart<1從映像的中間偏上開始漸層,越小越偏上。beginPart>1從映像的中間偏下開始漸層,越大越偏上。 
代碼如下: 

private int[] darkerPixels(BufferedImage originalPic, float beginPart) {// 得到圖片的寬度。int imageWidth = originalPic.getWidth();// 得到圖片的高度。int imageHeight = originalPic.getHeight();// 得到圖片的像素值。int totalBlocks = imageWidth * imageHeight;// 建立相處值的儲存空間。int[] pixels = new int[totalBlocks];// 儲存映像像素資訊。DirectColorModel dem = new DirectColorModel(24, 0xff0000, 0x00ff00,0x0000ff);float inc = 255f / imageHeight / beginPart;int int_inc = 100;float float_inc = 0;for (int i = 0; i < totalBlocks; i++) {if (i % imageHeight == 0 && i != 0) {float_inc = float_inc + inc;int_inc = (int) (float_inc);if (0 > int_inc) {int_inc = 0;}if (255 < int_inc) {int_inc = 255;}}int a = dem.getAlphaMask() / 2;int r = dem.getRed(pixels[i]) - int_inc;if (r < 0) {r = 0;}int g = dem.getGreen(pixels[i]) - int_inc;if (g < 0) {g = 0;}int b = dem.getBlue(pixels[i]) - int_inc;if (b < 0) {b = 0;}pixels[i] = a << 24 | r << 16 | g << 8 | b;}return pixels;}

3.利用改變後的像素點,產生一副新的圖片。代碼如下: 

public final BufferedImage getGradualImg(BufferedImage originalPic) {// 設定漸層的開發位置,1為中間位置,小於1開始位置偏上,大於1開始位置偏下。float beginPart = 1f;// 得到圖片的所有漸層後的像素點。int[] pixels = darkerPixels(originalPic, beginPart);int imageWidth = originalPic.getWidth();int imageHeight = originalPic.getHeight();MemoryImageSource memoryimagesource = new MemoryImageSource(imageWidth,imageHeight, new DirectColorModel(24, 0xff0000, 0x00ff00,0x0000ff), pixels, 0, imageWidth);Image imageBuf = null;try {memoryimagesource.setAnimated(true);memoryimagesource.setFullBufferUpdates(true);imageBuf = this.createImage(memoryimagesource);// 產生新的映像memoryimagesource.newPixels();} catch (NoSuchMethodError e) {e.printStackTrace();}BufferedImage changedImage = new BufferedImage(imageWidth, imageHeight,BufferedImage.TYPE_3BYTE_BGR);Graphics2D g2d = changedImage.createGraphics();g2d.drawImage(imageBuf, 0, 0, this);return changedImage;}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.