title: Retrieve album art using FFmpeg
body: <p>I'm developing an Android application that relies on FFmpeg to retrieve audio metadata. I know it's possible to retrieve album art programmatically using FFMpeg. However, once you have decoded the art (a video frame within an MP3) how do generate an image file (a PNG) for use within an application? I've search all over but can't seem to find a working example.</p>
  
  <p>Edit, here is the solution:</p>
  
  <pre><code>#include &lt;libavcodec/avcodec.h&gt;
  #include &lt;libavformat/avformat.h&gt;
  
  void retrieve_album_art(const char *path, const char *album_art_file) {
      int i, ret = 0;
  
      if (!path) {
          printf("Path is NULL\n");
          return;
      }
  
      AVFormatContext *pFormatCtx = avformat_alloc_context();
  
      printf("Opening %s\n", path);
  
      // open the specified path
      if (avformat_open_input(&amp;pFormatCtx, path, NULL, NULL) != 0) {
          printf("avformat_open_input() failed");
          goto fail;
      }
  
      // read the format headers
      if (pFormatCtx-&gt;iformat-&gt;read_header(pFormatCtx) &lt; 0) {
          printf("could not read the format header\n");
          goto fail;
      }
  
      // find the first attached picture, if available
      for (i = 0; i &lt; pFormatCtx-&gt;nb_streams; i++)
          if (pFormatCtx-&gt;streams[i]-&gt;disposition &amp; AV_DISPOSITION_ATTACHED_PIC) {
              AVPacket pkt = pFormatCtx-&gt;streams[i]-&gt;attached_pic;
              FILE* album_art = fopen(album_art_file, "wb");
              ret = fwrite(pkt.data, pkt.size, 1, album_art);
              fclose(album_art);
              av_free_packet(&amp;pkt);
              break;
          }
  
      if (ret) {
          printf("Wrote album art to %s\n", album_art_file);
      }
  
      fail:
          av_free(pFormatCtx);
          // this line crashes for some reason...
          //avformat_free_context(pFormatCtx);
  }
  
  int main() {
      avformat_network_init();
      av_register_all();
  
      const char *path = "some url";
      const char *album_art_file = "some path";
  
      retrieve_album_art(path, album_art_file);
  
      return 0;
  }
  </code></pre>