title: How to create a square bitmap from a rectangular bitmap in Android
body: <p>Basically, I have a rectangular bitmap and want to create a new Bitmap with squared dimensions which will contain the rectangular bitmap inside of it.</p>
  
  <p>So, for example, if the source bitmap has width:100 and height:400, I want a new bitmap with width:400 and height:400. Then, draw the source bitmap centered inside of this new bitmap (see attached image for a better understanding).</p>
  
  <p><img src="https://i.stack.imgur.com/FHBOt.png" alt="Example of the expected result"></p>
  
  <p>My code below creates the square bitmap fine, but the source bitmap is not being drawn into it. As a result, I'm left with a bitmap that is completely black.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>Bitmap sourceBitmap = BitmapFactory.decodeFile(sourcePath);
  
  Bitmap resultBitmap= Bitmap.createBitmap(sourceBitmap.getHeight(), sourceBitmap.getHeight(), Bitmap.Config.ARGB_8888);
  
  Canvas c = new Canvas(resultBitmap);
  
  Rect sourceRect = new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight());
  Rect destinationRect = new Rect((resultBitmap.getWidth() - sourceBitmap.getWidth())/2, 0, (resultBitmap.getWidth() + sourceBitmap.getWidth())/2, sourceBitmap.getHeight());
  c.drawBitmap(resultBitmap, sourceRect, destinationRect, null);
  
  // save to file
  File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");
  File file = new File(mediaStorageDir.getPath() + File.separator + "result.jpg");
  try {
      result.compress(CompressFormat.JPEG, 100, new FileOutputStream(file));
  } catch (FileNotFoundException e) {
      e.printStackTrace();
  }
  </code></pre>
  
  <p>Any idea what I'm doing wrong?</p>