जावा में छवियों को मैनिपुलेट करने से Graphics
या Graphics2D
संदर्भों का उपयोग करके हासिल किया जा सकता है।
जेपीईजी और पीएनजी जैसी छवियों को लोड करना ImageIO
कक्षा का उपयोग करके किया जा सकता है। ImageIO.read
विधि File
में पढ़ने और BufferedImage
लौटाती है, जिसका उपयोग Graphics2D
(या Graphics
, इसके सुपरक्लास) संदर्भ के माध्यम से छवि में हेरफेर करने के लिए किया जा सकता है।
Graphics2D
संदर्भ कई छवि ड्राइंग और हेरफेर कार्यों को करने के लिए उपयोग किया जा सकता है। जानकारी और उदाहरणों के लिए, Trail: 2D GraphicsThe Java Tutorials बहुत अच्छी शुरुआत होगी।
के बाद एक सरलीकृत उदाहरण (untested) जो एक JPEG फ़ाइल खुल जाएगा, और कुछ हलकों और लाइनों आकर्षित (अपवाद अनदेखी कर रहे हैं) है:
// Open a JPEG file, load into a BufferedImage.
BufferedImage img = ImageIO.read(new File("image.jpg"));
// Obtain the Graphics2D context associated with the BufferedImage.
Graphics2D g = img.createGraphics();
// Draw on the BufferedImage via the graphics context.
int x = 10;
int y = 10;
int width = 10;
int height = 10;
g.drawOval(x, y, width, height);
g.drawLine(0, 0, 50, 50);
// Clean up -- dispose the graphics context that was created.
g.dispose();
ऊपर कोड एक JPEG छवि खुल जाएगा, और एक आकर्षित अंडाकार और एक रेखा।एक बार इन ऑपरेशन को छवि में हेरफेर करने के लिए किया जाता है, BufferedImage
किसी अन्य Image
की तरह संभाला जा सकता है, क्योंकि यह Image
का उप-वर्ग है।
उदाहरण के लिए, एक ImageIcon
बनाने BufferedImage
का उपयोग करके, एक एक JButton
या JLabel
में छवि एम्बेड कर सकते हैं:
JLabel l = new JLabel("Label with image", new ImageIcon(img));
JButton b = new JButton("Button with image", new ImageIcon(img));
JLabel
और JButton
दोनों कंस्ट्रक्टर्स जो एक ImageIcon
में है, इसलिए है कि हो सकता है एक स्विंग घटक में एक छवि जोड़ने के लिए एक आसान तरीका है।