Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading Image file using scala

Tags:

scala

I am trying to downloading image file for Latex formula. Following is the code I am using

    var out: OutputStream = null;
    var in: InputStream = null;

    try {
      val url = new URL("http://latex.codecogs.com/png.download?$$I=\frac{dQ}{dt}$$")

      val connection = url.openConnection().asInstanceOf[HttpURLConnection]
      connection.setRequestMethod("GET")
      in = connection.getInputStream
      val localfile = "sample2.png"
      out = new BufferedOutputStream(new FileOutputStream(localfile))
      val byteArray = Stream.continually(in.read).takeWhile(-1 !=).map(_.toByte).toArray

      out.write(byteArray)
    } catch {
      case e: Exception => println(e.printStackTrace()) 
    } finally {
      out.close
      in.close
    }

I am able to download but it is not downloading complete image, expected image size is around 517 bytes but it is downloading only 275 bytes. What might be going wrong in it. Attached the incomplete and complete images. Please help me. I have used same code to download files more than 1MB size it worked properly.

Incomplete image

Expected image

like image 701
Srinivas Avatar asked Sep 04 '12 15:09

Srinivas


2 Answers

You're passing a bad string, the "\f" is interpreted as an escape sequence and gives you a single "form feed" character.

Better:

val url = new URL("http://latex.codecogs.com/png.download?$$I=\\frac{dQ}{dt}$$")

or

val url = new URL("""http://latex.codecogs.com/png.download?$$I=\frac{dQ}{dt}$$""")
like image 80
themel Avatar answered Nov 01 '22 21:11

themel


An alternative option is to use the system commands which is much cleaner

import sys.process._
import java.net.URL
import java.io.File

new URL("""http://latex.codecogs.com/png.download?$$I=\frac{dQ}{dt}$$""") #> new File("sample2.png") !!
like image 36
bryanlcampbell Avatar answered Nov 01 '22 20:11

bryanlcampbell