title: How to convert any image to JPG?
body: <p>I am receiving a <code>MultipartFile</code> Spring object from rest controller. I am trying to convert any  inage file to <code>JPG</code> image <strong>but I just need the byte array to save it</strong> on <code>mongoDb</code></p>
  <p>I found this code to do that</p>
  <pre><code>public boolean convertImageToJPG(InputStream attachedFile) {
      try {
          BufferedImage inputImage = ImageIO.read(attachedFile);
          ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
          boolean result = ImageIO.write(inputImage, &quot;jpg&quot;, byteArrayOutputStream);
          
          return result;
          
      } catch (IOException e) {
          
          System.err.println(&quot;Error &quot; + e);
          
      }
      return false;
  }
  </code></pre>
  <p>But <code>result</code> as a <code>false</code> with not error, so <code>ImageIO.write</code> is not working</p>
  <p>Also I found this to do the same but using <code>File</code> object, I don't want to <code>create</code> the file on directory, I just need the byte array</p>
  <pre><code>public static boolean convertFormat(String inputImagePath,
          String outputImagePath, String formatName) throws IOException {
          FileInputStream inputStream = new FileInputStream(inputImagePath);
          FileOutputStream outputStream = new FileOutputStream(outputImagePath);
           
          // reads input image from file
          BufferedImage inputImage = ImageIO.read(inputStream);
           
          // writes to the output image in specified format
          boolean result = ImageIO.write(inputImage, formatName, outputStream);
           
          // needs to close the streams
          outputStream.close();
          inputStream.close();
           
          return result;
      }
  </code></pre>
  <p><strong>Testing</strong></p>
  <pre><code>public class TestImageConverter {
   
      public static void main(String[] args) {
          String inputImage = &quot;D:/Photo/Pic1.jpg&quot;;
          String oututImage = &quot;D:/Photo/Pic1.png&quot;;
          String formatName = &quot;PNG&quot;;
          try {
              boolean result = ImageConverter.convertFormat(inputImage,
                      oututImage, formatName);
              if (result) {
                  System.out.println(&quot;Image converted successfully.&quot;);
              } else {
                  System.out.println(&quot;Could not convert image.&quot;);
              }
          } catch (IOException ex) {
              System.out.println(&quot;Error during converting image.&quot;);
              ex.printStackTrace();
          }
      }
  }
  </code></pre>
  <p>How can I solve my problem?</p>