Magnetoencephalography (MEG) and magnetic resonance imaging (MRI) are non-invasive imaging techniques that offer effective means for disease diagnosis. A more straightforward and optimized method is presented for designing gradient coils which are pivotal parts of the above imaging systems. A novel design method based on stream function combining an optimization algorithm is proposed to obtain highly linear gradient coil. Two-dimensional Fourier expansion of the current field on the surface where the coil is located and the equipotential line of the expansion term superposition according to the number of turns of the coil are used to represent the coil shape. Particle swarm optimization is utilized to optimize the coil shape while linearity and field uniformity are used as parameters to evaluate the coil performance. Through this method, the main parameters such as input current distribution region, coil turns, desired magnetic field strength, expansion order and iteration times can be combined in a given solution space to optimize coil design. Simulation results show that the maximum linearity spatial deviation of the designed bi-planar x-gradient coil compared with that of target field method is reduced from 14% to 0.54%, and that of the bi-planar z-gradient coil is reduced from 8.98% to 0.52%. Similarly, that of the cylindrical x-gradient coil is reduced from 2% to 0.1%, and that of the cylindrical z-gradient coil is reduced from 0.87% to 0.45%. The similar results are found in the index of inhomogeneity error. Moreover, it has also been verified experimentally that the result of measured magnetic field is consist with simulated result. The proposed method provides a straightforward way that simplifies the design process and improves the linearity of designed gradient coil, which could be beneficial to realize better magnetic field in engineering applications.