Wednesday, 3 November 2021

How to write BufferedImage object to a file?

Using 'ImageIO.write' method, you can write the image to a file.

 

public static boolean write(RenderedImage im, String formatName,File output) throws IOException

Writes an image using an arbitrary ImageWriter that supports the given format to a File. If there is already a File present, its contents are discarded.

 

Step 1: Get the instance of BufferedImage object.

private static BufferedImage getBufferedImage() {
	BufferedImage img = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);

	int r = 100;
	int g = 125;
	int b = 55;
	int col = (r << 8) | (g << 16) | b;
	for (int x = 0; x < 300; x++) {
		for (int y = 20; y < 500; y++) {
			img.setRGB(x, y, col);
		}
	}
	return img;
}

 

Step 2: Write buffered image to the file.

File fileToWrite = new File("/Users/Shared/test.png");
ImageIO.write(bufferedImage, "PNG", fileToWrite);

 

Find the below working application.

 

WriteBufferedImage.java

package com.sample.app.images;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class WriteBufferedImage {

	private static BufferedImage getBufferedImage() {
		BufferedImage img = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);

		int r = 100;
		int g = 125;
		int b = 55;
		int col = (r << 8) | (g << 16) | b;
		for (int x = 0; x < 300; x++) {
			for (int y = 20; y < 500; y++) {
				img.setRGB(x, y, col);
			}
		}
		return img;
	}

	public static void main(String args[]) throws IOException {
		BufferedImage bufferedImage = getBufferedImage();

		File fileToWrite = new File("/Users/Shared/test.png");

		ImageIO.write(bufferedImage, "PNG", fileToWrite);
	}
}

  Run above application and open the file "/Users/Shared/test.png", you will see below kind of screen.

 

  

 

 

 

Previous                                                    Next                                                    Home

Java: image programs

      How to write BufferedImage object to a file?

Java: How to replace a value in ArrayList or LinkedList

There are multiple ways to replace a value in ArrayList or LinkedList.

 

Approach 1: Using set method of List interface.

 

E set(int index, E element)

Replaces the element at the specified position in this list with the specified element.

 

ListReplaceElement.java

package com.sample.app.collections;

import java.util.ArrayList;
import java.util.List;

public class ListReplaceElement {

	public static void main(String args[]) {
		List<Integer> primes = new ArrayList<>();
		primes.add(2);
		primes.add(3);
		primes.add(5);

		System.out.println("primes -> " + primes);

		System.out.println("\nSetting the value at index 1 to 7\n");
		primes.set(1, 7);

		System.out.println("primes -> " + primes);

	}

}

 

Output

primes -> [2, 3, 5]

Setting the value at index 1 to 7

primes -> [2, 7, 5]

 

Approach 2: Using set method of ListIterator. This approach is useful while you want to replace the value while iterating.

 

Example

 

ListIterator<Integer> listIterator = primes.listIterator();
while (listIterator.hasNext()) {
	int val = listIterator.next();
	if (val == 3) {
		listIterator.set(7);
		break;
	}
}

Find the below working application.

 

ListReplaceElementUsingIterator.java

package com.sample.app.collections;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class ListReplaceElementUsingIterator {

	public static void main(String args[]) {
		List<Integer> primes = new ArrayList<>();
		primes.add(2);
		primes.add(3);
		primes.add(5);

		System.out.println("primes -> " + primes);

		System.out.println("\nReplacing the value 3 by 7\n");
		ListIterator<Integer> listIterator = primes.listIterator();
		while (listIterator.hasNext()) {
			int val = listIterator.next();
			if (val == 3) {
				listIterator.set(7);
				break;
			}
		}

		System.out.println("primes -> " + primes);

	}

}


Output

primes -> [2, 3, 5]

Replacing the value 3 by 7

primes -> [2, 7, 5]


Approach 3: Remove the element at specific index and add new element using add method.

 

Step 1: Remove element at the index.

Ex: primes.remove(1);

 

Step 2: Add new element at the index.

Ex: primes.add(1, 7);

 

Find the below working application.

 

ListReplaceElement1.java

package com.sample.app.collections;

import java.util.ArrayList;
import java.util.List;

public class ListReplaceElement1 {

	public static void main(String args[]) {
		List<Integer> primes = new ArrayList<>();
		primes.add(2);
		primes.add(3);
		primes.add(5);

		System.out.println("primes -> " + primes);

		System.out.println("\nReplacing the value 3 by 7\n");
		
		//Remove element at index 1
		primes.remove(1);
		//Add new element at the index 1
		primes.add(1, 7);

		System.out.println("primes -> " + primes);

	}

}


Output

primes -> [2, 3, 5]

Replacing the value 3 by 7

primes -> [2, 7, 5]

 

 

You may like

Interview Questions

Java: How to find maximum element in a collection?

Java: How to find the minimum element in a collection?

Java: Get the index of first occurrence of a substring

Java: Get the index of last occurrence of a substring

Java: Get all the indexes of occurrence of a substring

Tuesday, 2 November 2021

Java: Get all the fields and inherited fields of a class

In this post, I am going to explain how to get all the fields and inherited fields of a class.

 

Step 1: Get all the fields of current class using 'getDeclaredFields' method.

clazzTemp.getDeclaredFields()

Step 2: Get the super class of this class and repeat step 1 for this parent class. Do the steps 1 and 2 until the parent class is null.

 

clazzTemp.getSuperclass()

 

Example

public static List<Field> getAllFields(Class<?> clazz) {
	List<Field> fields = new ArrayList<Field>();
	Class<?> clazzTemp = clazz;

	do {
		fields.addAll(Arrays.asList(clazzTemp.getDeclaredFields()));
	} while ((clazzTemp = clazzTemp.getSuperclass()) != null);

	return fields;
}

Find the below working application.

 

AllFieldsOfAClass.java

package com.sample.app.fields;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AllFieldsOfAClass {

	public static class Parent {
		int parentA, parentB;
	}

	public static class Child extends Parent {
		private int childA, childB;
	}

	public static List<Field> getAllFields(Class<?> clazz) {
		List<Field> fields = new ArrayList<Field>();
		Class<?> clazzTemp = clazz;

		do {
			fields.addAll(Arrays.asList(clazzTemp.getDeclaredFields()));
		} while ((clazzTemp = clazzTemp.getSuperclass()) != null);

		return fields;
	}

	public static void main(String args[]) {

		getAllFields(Child.class).stream().forEach(field -> {
			System.out.println(field.getName());
		});
	}
}


Output

childA
childB
parentA
parent





 

 

Previous                                                    Next                                                    Home

Java: Get all the indexes of occurrence of a substring

Approach 1: Using indexOf method

 

public int indexOf(String str, int fromIndex)

Return the index of the first occurrence of the specified substring, starting at the specified index, or -1 if there is no such occurrence.

        

AllTheOccurrencesOfSubstring.java

package com.sample.app.strings;

public class AllTheOccurrencesOfSubstring {
	
	private static void printAllOccurrences(String str, String subStr) {
		int startIndex = -1;
		
		while((startIndex = str.indexOf(subStr, startIndex+1)) != -1) {
			System.out.println("index -> " + startIndex);
		}
	}

	public static void main(String args[]) {
		String str = "abrakadabra";

		printAllOccurrences(str, "ab");
	}

}

 

Output

index -> 0
index -> 7

 

Approach 2: Using regular expressions.

 

AllTheOccurrencesOfSubstring1.java

 

package com.sample.app.strings;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AllTheOccurrencesOfSubstring1 {

	private static void printAllOccurrences(String str, String subStr) {
		Pattern word = Pattern.compile(subStr);
		Matcher match = word.matcher(str);

		while (match.find()) {
			System.out.println("index -> " + match.start());
		}
	}

	public static void main(String args[]) {
		String str = "abrakadabra";

		printAllOccurrences(str, "ab");
	}

}

Output

index -> 0
index -> 7


You may like

Interview Questions

How method overloading works with null values in Java?

Java: How to find maximum element in a collection?

Java: How to find the minimum element in a collection?

Java: Get the index of first occurrence of a substring

Java: Get the index of last occurrence of a substring

Java: Get the index of last occurrence of a substring

Using ‘lastIndex’ method we can get the index of last occurrence of a substring.

 

public int lastIndexOf(String str)

Returns the index within this string of the last occurrence of the specified substring, or -1 if there is no such occurrence.

 

LastIndexDemo.java

package com.sample.app.strings;

public class LastIndexDemo {

	public static void main(String args[]) {
		String str = "abrakadabra";

		int brLastIndex = str.lastIndexOf("br");
		int xyLastIndex = str.lastIndexOf("xy");

		System.out.println("str -> " + str);
		System.out.println("brLastIndex " + brLastIndex);
		System.out.println("xyLastIndex -> " + xyLastIndex);
	}

}

 

Output

str -> abrakadabra
brLastIndex 8
xyLastIndex -> -1

 

Reference

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#lastIndexOf-java.lang.String-

 

 

  

You may like

Interview Questions

How to call a method asynchronously in Java?

How method overloading works with null values in Java?

Java: How to find maximum element in a collection?

Java: How to find the minimum element in a collection?

Java: Get the index of first occurrence of a substring

Java: Get the index of first occurrence of a substring

Approach 1: Using indexOf method.

String class provides ‘indexOf’ method, which takes a string as argument and returns the index within this string of the first occurrence of the specified substring. If this string does not contain any occurrence, then it returns -1.

 

Example

String str = "abrakadabra";
int brIndex = str.indexOf("br");

 

IndexOfDemo.java

package com.sample.app.strings;

public class IndexOfDemo {

	public static void main(String args[]) {
		String str = "abrakadabra";

		int brIndex = str.indexOf("br");
		int xyIndex = str.indexOf("xy");

		System.out.println("str -> " + str);
		System.out.println("brIndex -> " + brIndex);
		System.out.println("xyIndex -> " + xyIndex);
	}

}

 

Output

str -> abrakadabra
brIndex -> 1
xyIndex -> -1

 

Approach 2: Using regular expression.

 

IndexOfUsingRegexDemo.java

package com.sample.app.strings;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IndexOfUsingRegexDemo {

	public static void main(String args[]) {
		String str = "abrakadabra";

		Pattern word = Pattern.compile("br");
		Matcher match = word.matcher(str);

		while (match.find()) {
			System.out.println("Found \"br\" at index " + match.start());
			break;
		}

	}

}

 

Output

Found "br" at index 1

 

Reference

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#indexOf(java.lang.String)

 

 

 

You may like

Interview Questions

How HashSet behave while adding a duplicate value?

How to call a method asynchronously in Java?

How method overloading works with null values in Java?

Java: How to find maximum element in a collection?

Java: How to find the minimum element in a collection?