Advertisement
Guest User

Untitled

a guest
Jan 25th, 2020
639
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. package pl.project.fern;
  2.  
  3. import java.awt.image.BufferedImage;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.IOException;
  6.  
  7. import javax.imageio.ImageIO;
  8.  
  9. //import org.apache.commons.codec.binary.Base64;
  10.  
  11. import java.util.Base64;
  12.  
  13. public class BarnsleyFern {
  14. private int dim = 1080;
  15. private int bgColor = 0xFF000000;
  16. private int fernColor = 0xFF00FF00;
  17. private int iterations = 200000;
  18. String type = "jpg";
  19. BufferedImage img;
  20.  
  21. public String getFern(int bgColor, int fernColor, int iterations) {
  22. this.bgColor = bgColor;
  23. this.fernColor = fernColor;
  24. this.iterations = iterations;
  25. createFern();
  26. return this.encodeToString();
  27. }
  28.  
  29. void createFern() {
  30. double x = 0;
  31. double y = 0;
  32. img = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB);
  33.  
  34. for (int i = 0; i < dim; i++) {
  35. for (int j = 0; j < dim; j++) {
  36. img.setRGB(i, j, fernColor);
  37. }
  38. }
  39.  
  40. for (int i = 0; i < iterations; i++) {
  41. double tmpx, tmpy;
  42. double r = Math.random();
  43.  
  44. if (r <= 0.01) {
  45. tmpx = 0;
  46. tmpy = 0.16 * y;
  47. } else if (r <= 0.08) {
  48. tmpx = 0.2 * x - 0.26 * y;
  49. tmpy = 0.23 * x + 0.22 * y + 1.6;
  50. } else if (r <= 0.15) {
  51. tmpx = -0.15 * x + 0.28 * y;
  52. tmpy = 0.26 * x + 0.24 * y + 0.44;
  53. } else {
  54. tmpx = 0.85 * x + 0.04 * y;
  55. tmpy = -0.04 * x + 0.85 * y + 1.6;
  56. }
  57. x = tmpx;
  58. y = tmpy;
  59.  
  60. img.setRGB((int) Math.round(dim / 2 + x * dim / 11),
  61. (int) Math.round(dim - y * dim / 11), bgColor);
  62. }
  63. }
  64.  
  65. public String encodeToString() {
  66. String imageString = null;
  67. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  68.  
  69. try {
  70. ImageIO.write(this.img, type, bos);
  71. byte[] imageBytes = bos.toByteArray();
  72.  
  73. imageString = Base64.getEncoder().encodeToString(imageBytes);
  74.  
  75. bos.close();
  76. } catch (IOException e) {
  77. e.printStackTrace();
  78. }
  79. return imageString;
  80. }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement