When I change the String m1 to a 2D int array it runs super fast but now it takes over an hour to just loop 10 pictures also each picture takes almost double the time the first one took . Is there a way where I can improve my code so it runs faster as I need to save all values as one String in the end ?
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectOutput; import java.io.*; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.imageio.ImageIO; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.*; import java.awt.Color; import java.awt.image.BufferedImage; public class Convertt { static String[][] allImages = new String[304][76808]; static String m1 = ""; static int f = 0; public static void rgb1(Path path) throws IOException { File file = new File(String.valueOf(path)); BufferedImage img = ImageIO.read(file); for (int y = 0; y < img.getHeight(); y++) { for (int x = 0; x < img.getWidth(); x++) { int pixel = img.getRGB(x, y); Color color = new Color(pixel, true); int red = color.getRed(); int green = color.getGreen(); int blue = color.getBlue(); if (m1 == "") { m1 = (red + ":" + green + ":" + blue); System.out.println(m1); } else { m1 = m1 + ":" + red + ":" + green + ":" + blue; } } } f++; System.out.println("Done with" + f); } public static void main(String[] args) throws IOException { Path imgFolder = Paths.get("D:\swim\Frames1"); int k = 1; for (int i = 0; i < 273; i++) { rgb1(imgFolder.resolve("frames" + k + ".png")); k++; } System.out.println("done"); FileWriter writer = new FileWriter("D:\swim\Output\new1.csv"); writer.append(m1); } }
Advertisement
Answer
Your understanding of string performance may be the issue.
Strings are immuttable, so every change to a string makes a new String, it doesn’t alter the existing string.
if (m1=="") { m1=(red+":"+green+":"+blue); System.out.println(m1); } else { m1=m1+":"+red+":"+green+":"+blue; }
doesn’t create one string. It creates a string for the red value, then creates a string that containts that in addition to a “:”, and then creates a string that contains that in addition to the green value, and then creates a string that contains that in addition to the …. (and so on)
So instead use a StringBuilder, which is like a buffer of RAM that holds String contents which can be manipulated without creating new Strings. When you want the String value for the buffer, call .toString()
to create a new String.