Android development study notes convert LaTex mathematical function expression into picture form through API interface

  • 2020-11-03 22:36:08
  • OfStack

This article shows how to convert LaTeX mathematical function expressions to picture form through the API interface provided by codecogs.com and Google.com. Specific ideas are as follows:

(1) Obtain the LaTeX mathematical expression entered by the user through EditText, and then format the expression to facilitate network transmission.

(2) Send the formatted string to codecogs.com or Google.com via Http request.

(3) Obtain the data stream returned by the website, convert it into pictures and display it on ImageView.

The specific process is as follows:

1. Get and format the LaTeX mathematical expression

First of all, we LaTeX mathematical formula input in this web site and then return image, namely "http: / / latex. codecogs. com/gif latex & # 63; "Follow the formula we entered. Such as "http: / / latex. codecogs. com/gif latex & # 63; \alpha "displays 1 Greek letter \alpha. So we can just add the formula that we want to convert. It is important to note, however, that Spaces in network URL are sometimes automatically converted to a plus sign. So, we need to get rid of the whitespace when we transmit. Or convert it to "%20". Execute when Button clicks.

First, add network access:


<uses-permission android:name="android.permission.INTERNET"/>
String PicUrlCogs = "http://latex.codecogs.com/gif.latex?";
Url = new URL(PicUrlCogs + editText.getText().toString().replace(" ",""));
new MyDownloadTask().execute();         //  perform Http request 
while(!finishFlag) {}              //  Waiting for data to be received 
imageView.setImageBitmap(pngBM);        //  Display images 
finishFlag = false;               //  Identify return 

2. Send Http request

Here, we send the Http request as an asynchronous thread. First, get the URL address obtained in the previous step, then establish an Http link, then enter the returned data into the input stream, and finally decode the input stream into an image and display it in ImageView.


 protected Void doInBackground(Void... params) {
      try {
        URL picUrl = Url;              //  To obtain URL address 
         HttpURLConnection conn = (HttpURLConnection) picUrl.openConnection();
//        conn.setConnectTimeout(1000);       //  Establish a connection 
//        conn.setReadTimeout(1000);
        conn.connect();               //  Open the connection 
        if (conn.getResponseCode() == 200) {     //  Connection successful, return data 
          InputStream ins = conn.getInputStream(); //  Input data into the data stream 
          pngBM = BitmapFactory.decodeStream(picUrl.openStream()); //  Parse data stream 
          finishFlag = true;            //  Identification after data transfer 
          ins.close();               //  Turn off the data stream 
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      return null;
    }

Complete MyDownloadTask class code (in MainActivity) :

3. Display pictures

The network connection class established in the previous step, then instantiates a class within the Button click event to receive the data, and then displays the returned data in ImageView.


btnPreview.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        try {
          Url = new URL(PicUrlCogs + editText.getText().toString().replace(" ","")); //  Convert string 
          new MyDownloadTask().execute();         //  perform Http request 
          while(!finishFlag) {}              //  Waiting for data to be received 
          imageView.setImageBitmap(pngBM);        //  Display images 
          finishFlag = false;               //  Identify return 
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });

In this way, after entering the LaTeX formula, we click the PREVIEW button and the corresponding image will be displayed on ImageView. Since this article only discusses how to do the transformation and does not optimize the image, it may seem small. In addition, if you take the method of converting URL by removing Spaces, try to ensure that LaTeX expressions are strictly legal (for example, all cells are enclosed in {}).

Screenshot_2015-11-17-22-21-34 Screenshot_2015-11-17-22-23-00

Complete code:


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends Activity {
  private String PicUrlGoogle = "http://chart.apis.google.com/chart?cht=tx&chl=";
  private String PicUrlCogs = "http://latex.codecogs.com/gif.latex?";
  private Button btnPreview;
  private EditText editText;
  private ImageView imageView;
  private Bitmap pngBM;
  private URL Url;
  private boolean finishFlag = false;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnPreview = (Button) findViewById(R.id.btnPreview);
    imageView = (ImageView) findViewById(R.id.imageView);
    editText = (EditText) findViewById(R.id.editText);
    btnPreview.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        try {
          Url = new URL(PicUrlCogs + editText.getText().toString().replace(" ","")); //  Convert string 
          new MyDownloadTask().execute();         //  perform Http request 
          while(!finishFlag) {}              //  Waiting for data to be received 
          imageView.setImageBitmap(pngBM);        //  Display images 
          finishFlag = false;               //  Identify return 
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }
  @Override
  public void onDestroy() {
    super.onDestroy();
  }
  class MyDownloadTask extends AsyncTask<Void, Void, Void> {
    protected void onPreExecute() {
      //display progress dialog.
    }
    protected Void doInBackground(Void... params) {
      try {
        URL picUrl = Url;              //  To obtain URL address 
        HttpURLConnection conn = (HttpURLConnection) picUrl.openConnection();
//        conn.setConnectTimeout(1000);       //  Establish a connection 
//        conn.setReadTimeout(1000);
        conn.connect();               //  Open the connection 
        if (conn.getResponseCode() == 200) {     //  Connection successful, return data 
          InputStream ins = conn.getInputStream(); //  Input data into the data stream 
          pngBM = BitmapFactory.decodeStream(picUrl.openStream()); //  Parse data stream 
          finishFlag = true;            //  Identification after data transfer 
          ins.close();               //  Turn off the data stream 
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      return null;
    }
    protected void onPostExecute(Void result) {
      // dismiss progress dialog and update ui
    }
  }
}

The above content is the Android development study notes introduced by this site. It converts the LaTex mathematical function expression into picture form through the API interface. Hope you like it.


Related articles: