我需要将任何图像转换为字节数组以满足加密要求。我使用JProgressBar监视转换进度,以防所选图像很大:File p= new File("C:\");BufferedImage oImg = ImageIO.read(p);ByteArrayOutputStream ba = new ByteArrayOutputStream();ImageIO.write(oImg, "jpg", ba);ba.flush();ProgressBar pb = new ProgressBar();Thread thread = new Thread(pb);thread.join();pb.fireTask(ba.toByteArray());我定义了一个ProgressBar使用SwingWorker如下的类:public class ProgressBar extends JPanel implements Runnable { private JProgressBar progressBar; private Task task; private byte[] imgByteArray; public void run() { createGUI(); } // Create the GUI private void createGUI() { JFrame frame = new JFrame("Converting..."); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComponent newContentPane = new ProgressBar(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); JPanel panel = new JPanel(); progressBar = new JProgressBar(0, 100); progressBar.setBounds(20, 22, 419, 20); progressBar.setValue(0); progressBar.setStringPainted(true); panel.add(progressBar); add(panel); setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); frame.pack(); frame.setVisible(true); } /** * Firing the Task */ public void fireTask(byte[] imgArray) { System.arraycopy(imgArray, 0, imgByteArray, 0, imgByteArray.length); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); task = new Task(); task.execute(); } class Task extends SwingWorker<Void, Void> { @Override public Void doInBackground() { for (int i=0; i<=imgByteArray.length; i++){ progressBar.setValue(i); progressBar.repaint(); try{ Thread.sleep(50); } catch (InterruptedException err){ } } return null; }
添加回答
举报
0/150
提交
取消